<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>ShellScript脚本编程 | SanShui的个人博客</title><meta name="author" content="SanShui"><meta name="copyright" content="SanShui"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="ShellScript脚本编程">
<meta property="og:type" content="article">
<meta property="og:title" content="ShellScript脚本编程">
<meta property="og:url" content="https://huaiyuechusan.github.io/archives/d8093044.html">
<meta property="og:site_name" content="SanShui的个人博客">
<meta property="og:description" content="ShellScript脚本编程">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://wallpaper.csun.site/?19">
<meta property="article:published_time" content="2024-02-03T13:28:00.000Z">
<meta property="article:modified_time" content="2024-10-17T12:01:05.056Z">
<meta property="article:author" content="SanShui">
<meta property="article:tag" content="Liunx">
<meta property="article:tag" content="Shell脚本">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://wallpaper.csun.site/?19"><link rel="shortcut icon" href="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg"><link rel="canonical" href="https://huaiyuechusan.github.io/archives/d8093044"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'ShellScript脚本编程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-10-17 20:01:05'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/echarts@4.9.0/dist/echarts.min.js"></script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="/./css/runtime.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="SanShui的个人博客" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (true) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg" onerror="onerror=null;src='./img/config_img/蓝天.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://wallpaper.csun.site/?19')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">SanShui的个人博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">ShellScript脚本编程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-02-03T13:28:00.000Z" title="发表于 2024-02-03 21:28:00">2024-02-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-10-17T12:01:05.056Z" title="更新于 2024-10-17 20:01:05">2024-10-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Liunx/">Liunx</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">6.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>23分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="ShellScript脚本编程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><meta name="referrer" content="no-referrer" />

<h2 id="ShellScript脚本编程"><a href="#ShellScript脚本编程" class="headerlink" title="ShellScript脚本编程"></a>ShellScript脚本编程</h2><h3 id="Shell脚本入门"><a href="#Shell脚本入门" class="headerlink" title="Shell脚本入门"></a>Shell脚本入门</h3><h4 id="Shell是什么"><a href="#Shell是什么" class="headerlink" title="Shell是什么"></a>Shell是什么</h4><p>Shell英文是”壳”，Shell是一块包裹着系统核心的壳，处于操作系统的最外层。</p>
<p>Shell是一个用C语言编写的程序，它是用户使用Linux的桥梁。通过编写Shell命令发送给linuⅸ内核去执行，操作就是计算机硬件，所以Shell命令是用户操作计算机硬件的桥梁，Shell是命令，类似于Windows系统中的Dos命令。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221985.png" alt="image-20240118180308328"></p>
<p>同时它可以作为<strong>命令语言</strong>，它交互式解释和执行用户输入的命令或者自动地解释和执行预先设定好的一连串的命令；作为<strong>程序设计语言</strong>，它定义了各种变量和参数，并提供了许多在高级语言中才具有的控制结构，包括循环和分支。</p>
<p>为什么学习Shell脚本？</p>
<p>Shell脚本语言的好处是简单、易学、易用，适合处理文件和目录之类的对象，以简单的方式快速完成某些复杂的事情。通过Shell命令编程语言来提高Linux系统的管理工作效率。</p>
<h4 id="Shell的运行过程"><a href="#Shell的运行过程" class="headerlink" title="Shell的运行过程"></a>Shell的运行过程</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221986.png" alt="image-20240118180732072"></p>
<p>当用户下达指令给该操作系统的时候，时间上是把指令告诉shell,经过shell解释，处理后让内核做出相应的动作。系统的回应和输出的信息也由shl处理，然后显示在用户的屏幕上。</p>
<h4 id="Shell解析器"><a href="#Shell解析器" class="headerlink" title="Shell解析器"></a>Shell解析器</h4><p>查看linux系统centos支持的shell解析器</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cat /etc/shells</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221987.png" alt="image-20240118180939827"></p>
<p>打印输出当前centos默认的解析器是bash语法：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">echo $SHELL</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221988.png" alt="image-20240118180949730"></p>
<blockquote>
<p>其中：</p>
<ul>
<li>echo：用于打印输出数据到终端</li>
<li>$SHELL：是全局共享的读取解析器类型环境变量，所有的Shell程序都可以读取的变量</li>
</ul>
</blockquote>
<h4 id="Shell编写格式与执行方式"><a href="#Shell编写格式与执行方式" class="headerlink" title="Shell编写格式与执行方式"></a>Shell编写格式与执行方式</h4><h5 id="脚本格式"><a href="#脚本格式" class="headerlink" title="脚本格式"></a>脚本格式</h5><ol>
<li><p>脚本文件后缀名规范</p>
<p>Shell脚本文件就是一个文本文件，后缀名建议使用.sh结尾。</p>
</li>
<li><p>首行格式规范</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br></pre></td></tr></table></figure>
<p> 设置当前Shell脚本文件采用bash解析器运行脚本代码</p>
</li>
<li><p>注释格式</p>
<p>单行注释</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">注释内容</span></span><br></pre></td></tr></table></figure>
<p>多行注释</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">:&lt;&lt;!</span><br><span class="line"># 注释内容1 </span><br><span class="line"># 注释内容2</span><br><span class="line">!</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h5 id="脚本文件执行的三种方式"><a href="#脚本文件执行的三种方式" class="headerlink" title="脚本文件执行的三种方式"></a>脚本文件执行的三种方式</h5><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221989.png" alt="image-20240118181812661"></p>
<p>添加权限：<code>chmod a+x helloworld.sh</code></p>
<p>三种方式的区别：sh或bash执行脚本文件方式是直接使用Shell解析器运行脚本文件，不需要可执行权限，仅路径方式是执行脚本文件自己，需要可执行权限。</p>
<h4 id="解释执行多个命令"><a href="#解释执行多个命令" class="headerlink" title="解释执行多个命令"></a>解释执行多个命令</h4><p>案例：执行test.sh脚本，实现在/root/bjsxt/目录下创建一个onetest..txt,在onetest.txt文件中增加内容”hello onetest shell”</p>
<p>实现步骤：</p>
<ol>
<li><p>使用<code>mkdir</code>创建/root/bjsxt目录</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221990.png" alt="image-20240118182403442"></p>
</li>
<li><p>创建脚本文件</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221991.png" alt="image-20240118182700294"></p>
</li>
<li><p>编写脚本文件</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">在/root/bjsxt/目录下创建onetest.txt文件</span></span><br><span class="line">touch /root/bjsxt/onetest.txt</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">在onetest.txt文件中写入内容</span></span><br><span class="line">echo &quot;Hello Shell&quot; &gt;&gt; /root/bjsxt/onetest.txt</span><br></pre></td></tr></table></figure>
</li>
<li><p>执行脚本文件使用cat命令查看文件内容</p>
<p>​    <img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221992.png" alt="image-20240118182745532"></p>
</li>
</ol>
<h3 id="Shell变量"><a href="#Shell变量" class="headerlink" title="Shell变量"></a>Shell变量</h3><p>变量用于存储管理运行在内存中的数据。</p>
<p>变量的类型</p>
<ol>
<li>系统环境变量</li>
<li>自定义变量</li>
<li>特殊符号变量</li>
</ol>
<h4 id="系统环境变量"><a href="#系统环境变量" class="headerlink" title="系统环境变量"></a>系统环境变量</h4><p>系统环境变量是系统提供的共享变量，是linux系统加载Shell的配置文件中定义的变量共享给所有的Shell程序使用。</p>
<h5 id="Shell的配置文件分类"><a href="#Shell的配置文件分类" class="headerlink" title="Shell的配置文件分类"></a>Shell的配置文件分类</h5><ol>
<li><p>全局配置文件</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/etc/profile</span><br><span class="line">/etc/profile.d/*.sh</span><br><span class="line">/etc/bashrc</span><br></pre></td></tr></table></figure>
</li>
<li><p>个人配置文件</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">当前用户/.bash_profile</span><br><span class="line">当前用户/.bashrc</span><br></pre></td></tr></table></figure>
<p>一般情况下，我们都是直接针对全局配置进行操作。</p>
</li>
</ol>
<h5 id="环境变量的分类"><a href="#环境变量的分类" class="headerlink" title="环境变量的分类"></a>环境变量的分类</h5><p>在Liux系统中，环境变量按照其作用范围不同大致可以分为系统级环境变量和用户级环境变量。</p>
<p>系统级环境变量：Shell环境加载全局配置文件中的变量共享给所有用户所有Shell程序使用，全局共享。</p>
<p>用户级环境变量：Shell环境加载个人配置文件中的变共享当前用户的Shell程序使用，登录用户使用。</p>
<h5 id="查看当前Shell系统环境变量"><a href="#查看当前Shell系统环境变量" class="headerlink" title="查看当前Shell系统环境变量"></a>查看当前Shell系统环境变量</h5><p>查看当前Shell系统环境变量，命令： <code>env</code></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221993.png" alt="image-20240118183913779"></p>
<h5 id="查看所有变量"><a href="#查看所有变量" class="headerlink" title="查看所有变量"></a>查看所有变量</h5><p>命令：<code>set</code></p>
<h5 id="常用系统环境变量"><a href="#常用系统环境变量" class="headerlink" title="常用系统环境变量"></a>常用系统环境变量</h5><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221994.png" alt="image-20240118184152132"></p>
<p>【示例】查看PATH环境变量</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221995.png" alt="image-20240118184326233"></p>
<h4 id="自定义变量"><a href="#自定义变量" class="headerlink" title="自定义变量"></a>自定义变量</h4><h5 id="自定义变量分类"><a href="#自定义变量分类" class="headerlink" title="自定义变量分类"></a>自定义变量分类</h5><ol>
<li>自定义局部变量</li>
<li>自定义常量</li>
<li>自定义全局变量</li>
</ol>
<h4 id="自定义局部变量"><a href="#自定义局部变量" class="headerlink" title="自定义局部变量"></a>自定义局部变量</h4><p>就是在脚本或命令中定义，仅在当前shell实例中有效，其他shell启动的程序不能访问局部变量。</p>
<h5 id="变量定义规则"><a href="#变量定义规则" class="headerlink" title="变量定义规则"></a>变量定义规则</h5><ul>
<li>命名只能使用英文字母，数字和下划线，首个字符不能以数字开头。</li>
<li>中间不能有空格，可以使用下划线(_)。</li>
<li>不能使用Shell中的关键字作为变量名称。</li>
<li>在bash环境中，变量的默认类型都是字符串类型，无法直接进行数值运算。</li>
<li>变量的值如果有空格，必须使用双引号括起来。</li>
</ul>
<h5 id="定义变量语法"><a href="#定义变量语法" class="headerlink" title="定义变量语法"></a>定义变量语法</h5><p><code>变量名=变量值</code></p>
<p><strong>注意：==等号两边不能有空格==</strong></p>
<p>【示例】定义局部变量</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">定义变量</span></span><br><span class="line">a=10</span><br><span class="line">your_name=jack</span><br></pre></td></tr></table></figure>
<h5 id="查看变量"><a href="#查看变量" class="headerlink" title="查看变量"></a>查看变量</h5><p>查看变量的值方式：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">语法1：直接使用变量名查询</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">var_name</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">语法2：使用花括号</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;var_name&#125;</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">区别：花括号方式适合拼接字符串</span></span><br></pre></td></tr></table></figure>
<h5 id="删除变量"><a href="#删除变量" class="headerlink" title="删除变量"></a>删除变量</h5><p>使用unset命令可以删除变量。语法：</p>
<p><code>unset variable_name</code></p>
<p>变量被删除后不能再次使用。unset命令不能删除只读变量。</p>
<h4 id="自定义全局变量"><a href="#自定义全局变量" class="headerlink" title="自定义全局变量"></a>自定义全局变量</h4><h5 id="父子Shell环境介绍"><a href="#父子Shell环境介绍" class="headerlink" title="父子Shell环境介绍"></a>父子Shell环境介绍</h5><p>例如：有2个Shell脚本文件A.sh和B.sh</p>
<p>如果在A.sh脚本文件中执行了B.sh脚本文件，那么A.sh就是父Shell环境，B.sh就是子Shell环境。</p>
<h5 id="自定义全局变量-1"><a href="#自定义全局变量-1" class="headerlink" title="自定义全局变量"></a>自定义全局变量</h5><p>就是在当前脚本文件中定义全局变量，这个全局变量可以在当前Shell环境与子Shell环境中都可以使用</p>
<p>语法：</p>
<p><code>export var_namel var_name2</code></p>
<p>测试全局变量在子Shell中是否用，在父Shel中是否可用</p>
<p>实现步骤：</p>
<ol>
<li><p>创建2个脚本文件test1.sh和test2.sh</p>
<p>​    <img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221996.png" alt="image-20240118185927713"></p>
</li>
<li><p>编辑test1.sh</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">定义全局变量</span></span><br><span class="line">export a=100</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">执行test2.sh脚本文件</span></span><br><span class="line">sh test2.sh </span><br></pre></td></tr></table></figure>
</li>
<li><p>编辑test2.sh</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">输出全局变量</span></span><br><span class="line">echo &quot;全局变量a的值：$a&quot;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h5 id="自定义系统环境变量"><a href="#自定义系统环境变量" class="headerlink" title="自定义系统环境变量"></a>自定义系统环境变量</h5><p>/etc/profile定义存储自定义系统级环境变量数据，当前用户进入Shell环境初始化的时候会加载全局配置文件/etc/profile里面的环境变量，供给所有Shell程序使用，以后只要是所有Shel‖程序或命令使用的变量，就可以定义在这个文件中。</p>
<p>创建环境变量步骤：</p>
<ol>
<li><p>编辑/etc/profile全局配置文件</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">增加命令：定义变量 VAR1=VAR1，并导出为环境变量</span></span><br></pre></td></tr></table></figure>
<p><strong>注意：</strong>直接打开全局配置文件是在配置文件的最顶端，使用G可以快速到文件底部，gg重新回到文件的顶端。</p>
</li>
<li><p>重新加载置文件/etc/profile，因为配置文件修改后要立刻功加载里面的数据就需要重新加载，语法：</p>
<p><code>source /etc/profile</code></p>
</li>
<li><p>在Shell环境中读取系统级环境变量var1</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221997.png" alt="image-20240118211442150"></p>
</li>
</ol>
<h4 id="特殊符号变量"><a href="#特殊符号变量" class="headerlink" title="特殊符号变量"></a>特殊符号变量</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221998.png" alt="image-20240118211718305"></p>
<h5 id="特殊符号变量：-n"><a href="#特殊符号变量：-n" class="headerlink" title="特殊符号变量：$n"></a>特殊符号变量：<code>$n</code></h5><p><code>$n</code>：用于接收脚本文件执行时传入的参数，</p>
<p><code>$0</code>用于获取当前脚本文件名称。</p>
<p><code>$1</code>~<code>$9</code>代表获取第1个输入参数到第9个输入参数。</p>
<p>第10个以上参数获取参数的格式：<code>$&#123;数字&#125;</code>，否则无法获取。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试特殊符号变量 <span class="variable">$n</span></span></span><br><span class="line">echo &quot;脚本文件名： $0&quot;</span><br><span class="line">echo &quot;第一个参数： $1&quot;</span><br><span class="line">echo &quot;第二个参数： $2&quot;</span><br><span class="line">echo &quot;第三个参数： $3&quot;</span><br><span class="line">echo &quot;第九个参数： $9&quot;</span><br><span class="line">echo &quot;第十个参数： $10&quot;  # 参数有问题</span><br><span class="line">echo &quot;第十个参数： $&#123;10&#125;&quot;</span><br><span class="line">echo &quot;第11个参数： $&#123;11&#125;&quot;</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221999.png" alt="image-20240118212602737"></p>
<h5 id="特殊符号变量：-和"><a href="#特殊符号变量：-和" class="headerlink" title="特殊符号变量：$#和$*"></a>特殊符号变量：<code>$#</code>和<code>$*</code></h5><p><code>$#</code>是获取所有输入参数如的个数</p>
<p><code>$*(或$@)</code>：传递的参数作为一个字符串显示</p>
<p>【示例】<code>$#</code>和<code>$*</code>的使用</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试特殊符号变量 <span class="variable">$n</span></span></span><br><span class="line">echo &quot;脚本文件名： $0&quot;</span><br><span class="line">echo &quot;第一个参数： $1&quot;</span><br><span class="line">echo &quot;第二个参数： $2&quot;</span><br><span class="line">echo &quot;第三个参数： $3&quot;</span><br><span class="line">echo &quot;第九个参数： $9&quot;</span><br><span class="line">echo &quot;第十个参数： $10&quot;  # 参数有问题</span><br><span class="line">echo &quot;第十个参数： $&#123;10&#125;&quot;</span><br><span class="line">echo &quot;第11个参数： $&#123;11&#125;&quot;</span><br><span class="line">echo &quot;参数的个数： $#&quot;</span><br><span class="line">echo &quot;参数：$*&quot;</span><br><span class="line">echo &quot;参数：$@&quot;</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221000.png" alt="image-20240118213252605"></p>
<p><code>$*</code>与<code>$@</code>区别：</p>
<p>相同点：都是引用所有参数。</p>
<p>不同点：只有在双引号中体现出来。</p>
<p>​                <code>$*</code>获取的所有参数拼接为一个字符串，格式为：<code>&quot;$1 $2...$n&quot;</code></p>
<p>​                <code>$@</code>获取一组参数列表对像，格式为：<code>&quot;$1&quot; &quot;$2&quot;...&quot;$n&quot;</code></p>
<p>假设在脚本运行时写了三个参数1、2、3，则<code>$*</code>等价于<code>&quot;123&quot;</code>（传递了一个参数），而<code>$@</code>等价于<code>&quot;1&quot; &quot;2&quot; &quot;3&quot;</code>（传递了三个参数）。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试$*与<span class="variable">$@</span>的区别</span></span><br><span class="line">for i in &quot;$*&quot;</span><br><span class="line">do</span><br><span class="line">	echo $i</span><br><span class="line">done</span><br><span class="line">echo &quot;---------------&quot;</span><br><span class="line">for i in &quot;$@&quot;</span><br><span class="line">do</span><br><span class="line">	echo $i</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221001.png" alt="image-20240118214241636"></p>
<h5 id="特殊符号变量-1"><a href="#特殊符号变量-1" class="headerlink" title="特殊符号变量$?"></a>特殊符号变量<code>$?</code></h5><p><code>$?</code>用于获取上一个Shell命令的退出码，或者是函数的返回值。</p>
<p>每个Shell命令的执行都有一个返回值，这个返回值用于说明命令执行是否成功。一般来说，返回0代表命令代表执行成功，非0代表执行失败。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">function test_add()&#123;</span><br><span class="line">	echo &quot;调用函数&quot;</span><br><span class="line">	return 10</span><br><span class="line">&#125;</span><br><span class="line">test_add</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221002.png" alt="image-20240118225919217"></p>
<h5 id="特殊符号"><a href="#特殊符号" class="headerlink" title="特殊符号$$$$"></a>特殊符号$$$$</h5><p>$$$$:用于获取当前Shell环境的进程ID号。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221003.png" alt="image-20240119220128876"></p>
<h4 id="字符串变量"><a href="#字符串变量" class="headerlink" title="字符串变量"></a>字符串变量</h4><h5 id="字符串创建"><a href="#字符串创建" class="headerlink" title="字符串创建"></a>字符串创建</h5><p>字符串是shell编程中最常用最有用的数据类型（除了数字和字符串，也没啥其它类型好用了)，字符串可以用<strong>单引号</strong>，也可以用双引号，也可以<strong>不用引号</strong>。</p>
<p>【示例】</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建字符串使用单引号</span></span><br><span class="line">a=&#x27;aaaa&#x27;</span><br><span class="line">echo $a</span><br><span class="line">echo $&#123;a&#125;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建字符串使用双引号</span></span><br><span class="line">b=&quot;bbb&quot;</span><br><span class="line">echo $b</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建字符串不使用引号</span></span><br><span class="line">c=ccc</span><br><span class="line">echo $c</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">d=aa bb</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="built_in">echo</span> <span class="variable">$d</span></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">注意如果变量的值中间有空格，需要使用引号创建</span></span><br><span class="line">d=&quot;aa bb&quot;</span><br><span class="line">echo $d</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221004.png" alt="image-20240119220914783"></p>
<blockquote>
<p>三者区别：</p>
<ul>
<li><p>单引号里的任何字符都会原样输出，单引号字符串中的变量是无效的；双引号里可以有变量</p>
</li>
<li><p>字符串中还可以出现双引号的子字符串，但是需要转义</p>
</li>
<li>不被引号包围的字符串中出现变量时也会被解析，这一点和双引号””包围的字符串一样。字符串中不能出现空格，否则空格后边的字符串会作为其他命令解析（直接输出没有问题，但不能赋值给其它变量)</li>
</ul>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">a=&#x27;aaaa&#x27;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">输出字符串变量</span></span><br><span class="line">echo &#x27;hellosa&#x27;</span><br><span class="line">echo &quot;hello$a&quot;</span><br><span class="line">echo &quot;hello\&quot;$a\&quot;&quot;</span><br><span class="line">echo hello$a</span><br><span class="line">echo &quot;hello $a&quot;</span><br><span class="line">echo hello $a</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">赋值给其他变量</span></span><br><span class="line">str1=&quot;hello$a&quot;</span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">str1=hello <span class="variable">$a</span> <span class="comment"># 不允许</span></span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221005.png" alt="image-20240119221622482"></p>
<h5 id="获取字符串的长度"><a href="#获取字符串的长度" class="headerlink" title="获取字符串的长度"></a>获取字符串的长度</h5><p>获取字符串长度语法：</p>
<p><code>$&#123;#字符串变量名&#125;`

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取字符串长度</span></span><br><span class="line">a=&quot;abc&quot;</span><br><span class="line">b=&quot;123456&quot;</span><br><span class="line">echo &quot;字符串变量a的值：$a, 长度：$&#123;#a&#125;&quot;</span><br><span class="line">echo &quot;字符串变量b的值：$&#123;b&#125;, 长度：$&#123;#b&#125;&quot;</span><br></pre></td></tr></table></figure>

![image-20240119222044188](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192221006.png)

##### 字符串的拼接

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">name=&quot;jack&quot;</span><br><span class="line">age=22</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">无符号拼接</span></span><br><span class="line">str=$name$age</span><br><span class="line">echo $str</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">双引号拼接</span></span><br><span class="line">str=&quot;$name$age&quot;</span><br><span class="line">echo $str</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">混合拼接</span></span><br><span class="line">str=$name&#x27;,&#x27;$age</span><br><span class="line">echo $str</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">字符串拼接中间有空格需要使用双号</span></span><br><span class="line">str=&quot;$name $age&quot;</span><br><span class="line">echo $str</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">不支持，需要使用引号</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">str=<span class="variable">$name</span> <span class="variable">$age</span></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">echo</span>输出字符串中间可以有空格</span></span><br><span class="line">echo $name $age</span><br></pre></td></tr></table></figure>

##### 截取字符串

| 格式                     | 说明                                                         |
| ------------------------ | ------------------------------------------------------------ |
| $&#123;变量名:start:length&#125;   | 从string字符串的左边第start个字符开始，向右截取length个字符。<br/>start从0开始 |
| $&#123;变量名:start&#125;          | 从string字符串的左边第start个字符开始截取，直到最后          |
| $&#123;变量名:0-start:length&#125; | 从string字符串的右边第start个字符开始，向右截<br/>取length个字符，stat从1开始，代表右侧第一个字符 |
| $&#123;变量名:0-start&#125;        | 从string字符串的右边第start个字符开始截取，直到最后          |
| $&#123;变量名#*chars&#125;         | 从string字符串左边第一次出现`*chars`的位置开始，<br/>截取`*chars`右边的所有字符 |
| $&#123;变量名##*chars&#125;        | 从string字符串左边最后一次出现`*chars`的位置开<br/>始，截取`*chars`右边的所有字符 |
| # $&#123;变量名%chars*&#125;       | 从string字符串右边第一次出现`chars*`的位置开始，<br/>截取`chars*`左边的所有字符 |
| # $&#123;变量名%%chars*&#125;      | 从string字符串右边最后一次出现`chars*`的位置开<br/>始，截取`chars*`左边的所有字符 |



<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">截取字符串 <span class="variable">$&#123;变量名:start:length&#125;</span></span></span><br><span class="line">str=&quot;abcdefgabc&quot;</span><br><span class="line">sub_str=$&#123;str:1:3&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="variable">$&#123;变量名:start&#125;</span></span></span><br><span class="line">sub_str=$&#123;str:2&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="variable">$&#123;变量名:0-start:length&#125;</span></span></span><br><span class="line">sub_str=$&#123;str:0-3:5&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="variable">$&#123;变量名:0-start&#125;</span></span></span><br><span class="line">sub_str=$&#123;str:0-4&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="variable">$&#123;变量名#*chars&#125;</span>   不包括第一次出现的chars</span></span><br><span class="line">sub_str=$&#123;str#*a&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot; </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="variable">$&#123;变量名##*chars&#125;</span>  不包括最后一次出现的chars</span></span><br><span class="line">sub_str=$&#123;str##*a&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="variable">$&#123;变量名%chars*&#125;</span>   不包括第一次出现的chars</span></span><br><span class="line">sub_str=$&#123;str%b*&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="variable">$&#123;变量名%%chars*&#125;</span>  不包括最后一次出现的chars</span></span><br><span class="line">sub_str=$&#123;str%%b*&#125;</span><br><span class="line">echo &quot;sub_str:$sub_str&quot;</span><br></pre></td></tr></table></figure>

![image-20240119225130625](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401192252351.png)

#### 数组变量

bash支持一维数组（不支持多维数组），并且没有限定数组的大小。

类似于C语言，数组元素的下标由0开始编号。获取数组中的元素要利用下标，下标可以是整数或算术表达式，其值应大于或等于0。

##### 定义数组

在Shell中，用括号来表示数组，数组元素用"空格"符号分开。定义数组的一般形式为：

`array_name=(value0 value1 value2 value3)`

数组的值类型任意，个数不限

可以不使用连续的下标，而且下标的范围没有限制。

`array_name=([0]=value0 [3]=value3 [5]=value5)`

##### 读取数组

读取数组元素值的一般格式是：

`$&#123;数组名[下标]&#125;`

@或*获取数组中的所有元素

`$(array_name[@])`

`$(array_name[*])`

获取数组的长度或个数

`$(#array_name[@])`

`$(#array_name[*]`

获取数组指定元素的字符长度

`$&#123;#array_name[索引]&#125;`

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">定义数组</span></span><br><span class="line">arr1=(21 33 &quot;abc&quot; &#x27;123&#x27;)</span><br><span class="line">arr2=(1 2 3 4)</span><br><span class="line">arr3=([0]=10 [1]=20 [3]=30 [4]=40 [6]=60)</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">根据下标获取数组元素的值</span></span><br><span class="line">echo &quot;获取arr1数组第1个元素的值：$&#123;arr1[0]&#125;&quot;</span><br><span class="line">echo &quot;获取arr3数组第7个元素的值：$&#123;arr3[6]&#125;&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取数组中的所有元素</span></span><br><span class="line">echo &quot;获取arr1数组中的所有元素：$&#123;arr1[@]&#125;&quot;</span><br><span class="line">echo &quot;获取arr2数组中的所有元素：$&#123;arr2[*]&#125;&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取数组的长度</span></span><br><span class="line">echo &quot;获取arr1数组的长度：$&#123;#arr1[@]&#125;&quot;</span><br><span class="line">echo &quot;获取arr2数组的长度：$&#123;#arr2[*]&#125;&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取数组指定元素的字符长度</span></span><br><span class="line">echo &quot;获取arr1数组中第4个元素的长度：$&#123;#arr1[3]&#125;&quot;</span><br></pre></td></tr></table></figure>

##### 数组拼接

所谓的数组拼接就是将两个数组连接成一个数组。

语法：使用`@`和`*`获取数组所有元素之后进行拼接。

`new_array=($&#123;array1[@]&#125; $&#123;array2[@]&#125; ...)`

`new_array=($&#123;array1[*])&#125; $&#123;array2[*]&#125; ...)`

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">定义数组</span></span><br><span class="line">arr1=(1 2 3 4 5 6)</span><br><span class="line">arr2=(a b c d e f g)</span><br><span class="line">echo &quot;输出数组中所有元素：&quot;</span><br><span class="line">echo &quot;arr1数组中的所有元素：$&#123;arr1[@]&#125;&quot;</span><br><span class="line">echo &quot;arr2数组中的所有元素：$&#123;arr2[*]&#125;&quot;</span><br><span class="line">echo &quot;数组的拼接：&quot;</span><br><span class="line">new_arr=($&#123;arr1[@]&#125; $&#123;arr2[*]&#125;)</span><br><span class="line">echo &quot;拼接后数组：$&#123;new_arr[*]&#125;&quot;</span><br></pre></td></tr></table></figure>

##### 数组删除

删除数组可以删哪除数组中指定元素，也可以删除整个数组。

删除数组中指定元素语法格式：

`unset array_name[index]`

删除整个数组

`unset array_name`

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">定义数组</span></span><br><span class="line">arr1=(1 2 3 4 5 6)</span><br><span class="line">arr2=(a b c d e f g)</span><br><span class="line">echo &quot;输出数组中所有元素：&quot;</span><br><span class="line">echo &quot;arr1数组中的所有元素：$&#123;arr1[@]&#125;&quot;</span><br><span class="line">echo &quot;arr2数组中的所有元素：$&#123;arr2[*]&#125;&quot;</span><br><span class="line">echo &quot;数组元素的删除：&quot;</span><br><span class="line">unset arr1[0] </span><br><span class="line">echo &quot;删除后输出arr1中的所有元素：$&#123;arr1[@]&#125;&quot;</span><br><span class="line">echo &quot;数组的删除：&quot;</span><br><span class="line">unset arr2</span><br><span class="line">echo &quot;删除arr2数组后：$&#123;arr2[*]&#125;&quot;</span><br></pre></td></tr></table></figure>

### Shell内置命令

#### 内置命令介绍

Shell内置命令，就是由Bash Shell自身提供的命令，而不是文件系统的可执行脚本文件。

使用type来确定一个命令是否是内置命令：

`type 命令`

![image-20240122235544837](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401231733980.png)

由此可见，cd是一个Shell内建命令，而ifconfig是一个外部文件，它的位置是/sbin/ifconfig。

通常来说，内置命令会比外部命令执行得更快，执行外部命令时不但会触发磁盘I/O还需要开启一个单独的进程来执行，执行完成后再退出。而执行内置命令相当于调用当前Shell进程的一个函数，还是在当前Shell环境进程内，减少了上下文切换。

Bash Shell中常用的内建命令

![image-20240122235750440](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401231733981.png)

#### alias：给命令创建别名

alisa用来给命令创建一个别名。若直接输入该命令且不带任何参数，则列出当前Shell进程中使用了哪些别名。

![image-20240122235920906](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401231733982.png)

##### 使用alias命令自定义别名

使用alias命令自定义别名的语法格式为：

`alias 别名='命令'`

设置查看进程的别名

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">alias pslist=&#x27;ps -aux&#x27;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">这样使用pslist和输入ps-aux可以达到同样的效果</span></span><br></pre></td></tr></table></figure>

 删除别名

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">unalias pslist </span><br></pre></td></tr></table></figure>

#### echo命令：输出字符串

echo是一个Shell内建命令，用来在终端输出字符串，并在最后**默认加上换行符**。

#####  echo不换行输出

echo命令输出结束后默认会换行，如果不希望换行，可以加上`-n`参数。

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">echo -n &quot;echo不换行输出测试&quot;</span><br></pre></td></tr></table></figure>

##### -e参数

默认情况下，echo不会解析以反斜杠开头的转义字符。比如，\n表示换行，echo默认会将它作为普通字符对待。

![image-20240123171639483](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401231733983.png)

#### read命令：读取从键盘输入的数据

read是Shell内置命令，用来从标准输入中读取数据并赋值给变量。如果没有进行重定向，默认就是从键盘读取用户输入的数据；如果进行了重定向，那么可以从文件中读取数据。

read命令的用法为：  

`read [-options] [variables]`

options表示选项，如下表所示；variables表示用来存储数据的变量，可以有一个，也可以有多个。

options和variables都是可选的，如果没有提供变量名，那么读取的数据将存放到环境变量REPLY。

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试<span class="built_in">read</span>内置命令的使用</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">不指定选项及变量</span></span><br><span class="line">read</span><br><span class="line">echo &quot;没有指定变量获取值：$REPLY&quot;</span><br><span class="line">read a</span><br><span class="line">echo &quot;指定变量获取值：$a&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">添加选项 -p</span></span><br><span class="line">read -p &quot;请输入姓名：&quot; name</span><br><span class="line">read -p &quot;请输入年龄：&quot; age</span><br><span class="line">echo &quot;姓名：$name, 年龄：$age&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">read</span> 参数 -n num</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取两个字符</span></span><br><span class="line">read -n 2 -p &quot;获取输入字符串&quot; str</span><br><span class="line">echo &quot;读取输入内容：$str&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">read</span> 参数 -s</span></span><br><span class="line">read -sp &quot;请输入密码：&quot; password</span><br><span class="line">read -sp &quot;请输入确认密码：&quot; repassword</span><br><span class="line">echo &quot;密码：$password， 确认密码：$repassword&quot;</span><br><span class="line">if [ $password == $repassword ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;密码和确认密码一致&quot;</span><br><span class="line">else </span><br><span class="line">	echo &quot;密码和确认密码不一致&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">read</span> 参数 -t</span></span><br><span class="line">read -t 5 -p &quot;输入有时间限制，请在5秒内输入：&quot; str</span><br><span class="line">echo &quot;输入内容：$str&quot;</span><br></pre></td></tr></table></figure>

read命令支持的选项及options支持的参数

![image-20240123172315834](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401231733984.png)

![image-20240123173256121](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401231733985.png)

#### exit命令

exit是一个Shell内置命令，用来退出当前Shell进程，并返回一个退出状态；使用`$?`可以接收这个退出状态。

exit命令可以接受一个整数值作为参数，代表退出状态。如果不指定，默认状态值是0。

exit退出状态只能是一个介于0~255之间的整数，其中只有0表示成功，其它值都表示失败。

【示例】Shell脚本文件中使用exit退出

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">echo &quot;exit命令示例&quot;</span><br><span class="line">exit 3</span><br><span class="line">echo &quot;hello exit命令&quot;</span><br></pre></td></tr></table></figure>

#### declare命令

declare命令的用法如下所示：

`declare [+/-] [aAirfx] [变量名=变量值]`

其中，-表示设置属性，+表示取消属性，aAifⅸ都是具体的选项，它们的含义如下表所示：

![image-20240123180532149](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132996.png)



<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试 + -</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">设置一个整数变量</span></span><br><span class="line">declare -i age=20</span><br><span class="line">echo &quot;整数变量：$age&quot;</span><br><span class="line">age=aaa</span><br><span class="line">echo &quot;整数变量age: $age&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">取消变量设置</span></span><br><span class="line">declare +i age</span><br><span class="line">age=bbbb</span><br><span class="line">echo &quot;取消age设置后age的值: $age&quot;</span><br><span class="line">设置只读变量</span><br><span class="line">declare -r pi=3.14</span><br><span class="line">echo &quot;只读变量pi的值：$pi&quot;</span><br><span class="line">p1=3.3333</span><br><span class="line">echo &quot;只读变量pi的值：$pi&quot;</span><br></pre></td></tr></table></figure>

![image-20240123194411183](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132997.png)

实现key-value关联数组变量语法

关联数组也称为"键值对(key-value)"数组，键(key）也即字符串形式的数组下标，值(value)也即元素值。

`declare -A 关联数组变量名=([字符串key1]=值1 [字符串key2]=值2 ...)`

declare也可以用于定义普通索引数组，`-a`参数创建普通或索数组 `-A`创建关联数组。

`declare -a 普通数组变量名=(值1 值2 ...）`

`declare -a 普通数组变量名=([0]=值1 [1]=值2 ...)`

 获取指定key的值

`$&#123;关联数组变量名[key]&#125;`

获取所有值

`$&#123;关联数组变量名[*]&#125;`

`$&#123;关联数组变量名[@]&#125;`

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建普通数组</span></span><br><span class="line">declare -a arr1=(10 20 30 &quot;abc&quot;)</span><br><span class="line">declare -a arr2=([0]=&quot;baizhan&quot; [2]=a [3]=10 [7]=70)</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取数组元素</span></span><br><span class="line">echo &quot;数组arr1中第2个元素：$&#123;arr1[1]&#125;&quot;</span><br><span class="line">echo &quot;数组arr2中第8个元素：$&#123;arr2[7]&#125;&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取数组中所有元素</span></span><br><span class="line">echo &quot;数组arr1中所有的元素：$&#123;arr1[*]&#125;&quot;</span><br><span class="line">echo &quot;数组arr2中所有的元素：$&#123;arr2[@]&#125;&quot;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建关联数组</span></span><br><span class="line">declare -A arr1=([&quot;aa&quot;]=10 [&quot;bb&quot;]=20 [&quot;cc&quot;]=30)</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取关联数组的值</span></span><br><span class="line">echo &quot;获取关联数组的值；$&#123;arr1[&quot;aa&quot;]&#125;&quot;</span><br><span class="line">echo &quot;获取关联数组的值：$&#123;arr1[&quot;cc&quot;]&#125;&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取关联数组的所有元素</span></span><br><span class="line">echo &quot;数组中所有元素的值：$&#123;arr1[*]&#125;&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取数组的长度</span></span><br><span class="line">echo &quot;数组的长度：$&#123;#arr1[*]&#125;&quot;</span><br></pre></td></tr></table></figure>

###  Shell运算符

Shell和其他编程语言一样，支持多种运算符，包括：

- 算数运算符
- 关系运算符
- 逻辑运算符
- 文件测试运算符

原生bash不支持简单的数学运算，需要通过其他命令来实现，如eXpr。

expr是evaluate expressions的缩写，译为"求值表达式”。Shell expr是一个功能强大，并且比较复杂的命令，它除了可以实现整数计算，还可以结合一些选对字符串进行处理，例如计算字符串长度、字符串比较、字符串匹配、字符串提取等。

expr语法：

`expr 算术运算符表达式`

获取计算结果赋值给新变量语法：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">result=`expr 算术运算符表达式`</span><br></pre></td></tr></table></figure>

注意：这里不是单引号是**反引号**。运算表达式运算符两边必须要有空格。运算不能是小数远算必须是整数运算。

`expr 10 + 10`

#### 算数运算符

![image-20240123204527943](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132998.png)

![image-20240123204603888](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132999.png)

 注意：条件表达式要放在方括号之间，并且要有空格，例如：`[$a==$b]`是错误的，必须写成`[ $a == $b ]`。

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试算术运算符</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">输入两个整数</span></span><br><span class="line">read -p &quot;请输入第一个数：&quot; a</span><br><span class="line">read -p &quot;请输入第二个数：&quot; b</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">输出输入的值</span></span><br><span class="line">echo &quot;a:$a, b:$b&quot;</span><br><span class="line">result=`expr $a + $b`</span><br><span class="line">echo &quot;加法的结果：$result&quot;</span><br><span class="line">result=`expr $a - $b`</span><br><span class="line">echo &quot;减法的结果：$result&quot;</span><br><span class="line">result=`expr $a \* $b`</span><br><span class="line">echo &quot;乘法的结果：$result&quot;</span><br><span class="line">result=`expr $a / $b`</span><br><span class="line">echo &quot;除法的结果：$result&quot;</span><br><span class="line">result=`expr $a % $b`</span><br><span class="line">echo &quot;取余的结果：$result&quot;</span><br></pre></td></tr></table></figure>

#### 比较运算符

##### 整数处比较运算符

假定变量a为10，变量b为20：

![image-20240123205455324](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132000.png)

![image-20240123205538603](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132001.png)

##### 字符串比较运算符

字符串比较运算符可以比较2个变量，变量的类型可以为**数字（整数，小数）与字符串**。

下表列出了常用的字符串运算符，假定变量a为"abc",变量b为"efg"。

字符串比较可以使用`[[]]`和`[]`2种方式。

![image-20240123212219672](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132002.png)

![image-20240123212426794](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132003.png)

字符串比较没有`<=`可以通过`[[ "a" < "b" || "a" == "b"]]`

`[[]]`和`[]`的区别

由于(())只能比较整数，不能比较小数和字符串所以不建议使用。

区别1：`[]`会产生单词分隔现象，`[[]]`不会产生单词分隔

![image-20240123212926474](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132004.png)

区别2：`[]`需要对`>`和`<`进行转义

![image-20240123213033152](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401232132005.png)

#### 布尔运算符

下表列出了常用的布尔运算符，假定变量a为10，变量b为20：

![image-20240124223257317](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848212.png)

![image-20240124223316183](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848213.png)

:warning:注意：布尔运算符必须放在`[]`或与test命令配合使用才有效

![image-20240124223408186](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848214.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">布尔运算符使用到<span class="keyword">if</span>条件中</span></span><br><span class="line">if [ ! $a \&gt; $b ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;a变量的值小于等于b&quot;</span><br><span class="line">else </span><br><span class="line">	echo &quot;a变量的值大于b&quot;</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">str=&quot;abc&quot;</span><br><span class="line">if [ $str -o 1 == 2 ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;条件成立&quot;</span><br><span class="line">else </span><br><span class="line">	echo &quot;条件不成立&quot;</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">if [ $str -a 1 == 2 ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;条件成立&quot;</span><br><span class="line">else </span><br><span class="line">	echo &quot;条件不成立&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

#### 逻辑运算符

假定变量a为10，变量b为20：

![image-20240128171756753](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848215.png)

![image-20240128171816913](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848216.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">a=100</span><br><span class="line">b=200</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">布尔运算符 [] ！-o -a</span></span><br><span class="line">if [ $a \&lt; $b -o 10 == 100 ]</span><br><span class="line">then</span><br><span class="line">	echo&quot;布尔运算符：条件成立”</span><br><span class="line">else</span><br><span class="line">	echo&quot;布尔运算符：条件不成立&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">逻辑运算符[[]]</span></span><br><span class="line">if [[ $a -lt $b || 10 == 100 ]]</span><br><span class="line">then</span><br><span class="line">	echo&quot;逻辑运算符条件成立&quot;</span><br><span class="line">else</span><br><span class="line">	echo&quot;逻辑运算符条件不成立&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

#### 文件测试运算符

文件测试运算符用于检查文件，如检查文件是否存在、是否可读、是否可执行、是否为空、是否可写、是否是目录、是否是普通文件。

属性检测描述如下：

![image-20240128172831527](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848217.png)

![image-20240128172923850](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848218.png)

![image-20240128173005607](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848219.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">文件测试运算符</span></span><br><span class="line">file=/root/test_shell/test_suanshu.sh</span><br><span class="line">if [ -e $file ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件存在&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不存在&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">判断文件是普通文件吗</span></span><br><span class="line">if [ -f $file ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件是普通文件&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不是普通文件&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">判断文件是目录吗</span></span><br><span class="line">if [ -d $file ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件是目录&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不是目录&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">判断文件是否为空</span></span><br><span class="line">if [ -s $file ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件不为空&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件为空&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">判断文件是否可读 可写 可执行</span></span><br><span class="line">if [-r $file ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件可读&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不可读”</span><br><span class="line">fi</span><br><span class="line">if [ -w $file ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件可写&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不可写&quot;</span><br><span class="line">fi</span><br><span class="line">if [ -x $file ]</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件可执行&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不可执行&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

### 计算命令

要想让数学计算发挥作用，必须使用数学计算命令，shell中常用的数学计算命令如下表所示。

![image-20240128175037025](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848220.png)

#### expr命令

##### expr用于求表达式的值

语法：

`expr 算术运算符表达式`

【示例】expr求表达式的值

![image-20240128175253188](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848221.png)

【示例】expr表达式的值赋给变量

![image-20240128175346258](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848222.png)

##### expr在字符串中的使用

**计算字符串的长度**

`expr length 字符串`

【示例】计算字符串的长度

![image-20240128175540534](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848223.png)

**截取字符串**

`expr substr 字符串 start len`

start：截取字符串的起始位置，从1开始

len：截取字符串的个数

![image-20240128175807487](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848224.png)

**获取第一个字符在字符串中出现的位置**

`expr index 被查找字符串 需要查找的字符`

【示例】获取第一个字符在字符串中出现的位置

![image-20240128175925474](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848225.png)

**正则表达式匹配语法1**

`expr match 字符串 正则表达式`

返回值为符合匹配字符串的长度，否则返回为0

【示例】正则表达式匹配语法1

![image-20240128180043255](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848226.png)

**正则表达式匹配语法2**

`expr 字符串 : 正则表达式`

返回值为符合匹配字符串的长度，否则返回为0

【示例】正则表达式匹配语法2

![image-20240128180147291](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848227.png)

#### (())命令

能够使用`(())`进行**整数**的数学运算。将数学运算表达式放到`((`和`))`之间，可以使用`$`获取`(())`表达式命令的结果，这和使用`$`获得变量值是一样的。

语法：

`((表达式))`

用法：

![image-20240128180640310](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848228.png)

![image-20240128180919201](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848229.png)

![image-20240128181502042](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848230.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">(())命令的使用</span></span><br><span class="line">((a=10+20))</span><br><span class="line">((b=a-10))</span><br><span class="line">((c=a+b))I</span><br><span class="line">echo &quot;a=$a,b=$b,c=$c&quot;</span><br><span class="line"></span><br><span class="line">a=$((10+20))</span><br><span class="line">b=$((a-10))</span><br><span class="line">c=$((a+b))</span><br><span class="line">echo &quot;a=$a,b=$b,c=$c&quot;</span><br><span class="line"></span><br><span class="line">if ((a&gt;10 &amp;&amp; a==c))</span><br><span class="line">then</span><br><span class="line">	echo &quot;a&gt;10 &amp;&amp; a==c&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;不成立&quot;</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">echo $((100+100))</span><br><span class="line">((a=10+20,b=a-10,c=a+b))</span><br><span class="line">echo &quot;a=$a,b=$b,c=$c&quot;</span><br></pre></td></tr></table></figure>

==注意：符号之间有无空格都可以，((a = 1 + 2))等价于((a=1+2))==

#### let命令

能够使用let进行整数的数学运算赋值。let命令和双小括`(())`在数字计算方面功能一样，但是没有`(())`功能强大，**let只能用于赋值计算，不能直接输出，不可以条件判断。**

语法：

`let 赋值表达式`

多个表达式赋值语法：

`let 变量名1=值1 变量名2=值2 …`

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">let</span>命令的使用</span></span><br><span class="line">let a=10+20</span><br><span class="line">let b=a-10</span><br><span class="line">let c=a+b</span><br><span class="line">echo &quot;a=$a,b=$b,c=$c&quot;</span><br><span class="line">echo&quot;a=$&#123;a&#125;,b=$&#123;b&#125;,c=$&#123;c&#125;&quot;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">let</span>命令用于多个赋值表达式</span></span><br><span class="line">let a=10+20 b=a-10 c=a+b</span><br><span class="line">echo &quot;a=$a,b=$b,c=$c&quot;</span><br></pre></td></tr></table></figure>

#### $[]命令

和`(())`和Iet命令类似，`$[]`也只能进行整数运算，但是只能对==单个表达式==的计算求值与输出。

语法：

`$[表达式]`

1. `$[]`会对表达式进行计算，并取得计算结果
2. 表达式内部不可以赋值给变量

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">a=$[10+20]</span><br><span class="line">b=$[a-10]</span><br><span class="line">c=$[a+b]</span><br><span class="line">echo &quot;a=$a,b=$b,c=$c&quot;</span><br></pre></td></tr></table></figure>



**执行整数表达式命令总结：**

![image-20240128184037358](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848231.png)

#### bc命令

Bash shell内置了对整数运算的支持，但是并不支持浮点运算，而linux bc命令可以很方便的进行**浮点运算**。bc命令是Liux简单的计算器，能进行进制转换与计算。能转换的进制包括十六进制、十进制、八进制、二进制等。可以使用的运算符号包括(+)加法、(-)减法、(*)乘法、(/)除法、(^)指数、(%)余数等。

语法：

`bc [options] [参数]`

options选项

![image-20240128184322212](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848232.png)

默认使用bc命令后回车会有很多欢迎信息，可以使用`bc -q`回车后不会有欢迎信息。

![image-20240128184440963](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848234.png)

##### 基本使用

![image-20240128184534981](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281851111.png)

【示例】**bc命令执行计算任务的文件**

创建一个文件test task.txt

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">108*67+123456</span><br><span class="line">58+2008*11</span><br><span class="line">3.14*43+187.23</span><br></pre></td></tr></table></figure>

执行任务文件计算每行表达式的值

`bc -q test_task.txt`

##### 内置变量的使用

![image-20240128184602906](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848236.png)

![image-20240128184805504](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848237.png)

![image-20240128184850023](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401281848238.png)

##### 内置数学函数的使用

内置数学函数

![image-20240128185226330](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218209.png)

![image-20240128185323846](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218210.png)

【示例】bc中内置的数学函数的使用

使用内置函数时必须使用`bc -ql`

![image-20240128185419073](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218211.png)

##### 非互动式的运算

**直接进行bc的表达式计算输出**

`echo "expression" | bc [options]`

expression：表达式必须符合bc命令要求的公式

​						表达式里面可以引用shell变量

例如：shell变量a=2在表达式里面引用的语法：$a

【示例】bc中非互动式的运算

![image-20240128185708958](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218213.png)

![image-20240128185809295](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218214.png)

##### 将bc计算的结果赋值给shell变量

语法格式：

#第一种方式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var name=`echo &quot;expression&quot; | bc [options]`</span><br></pre></td></tr></table></figure>

#第二种方式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var name=$(echo &quot;expression&quot; | bc [options])</span><br></pre></td></tr></table></figure>

`$()`与``功能一样，都是执行里面的命令

区别：

``是所有linux系统支持的方式，兼容性较好，但是容易与引号产生混淆。

`$()`不是所有linux系统都支持的方式。兼容性较差，但是不容易产生混淆。

【示例】将bc计算的结果赋值给shell变量

![image-20240128191808459](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218215.png)

##### 非互动式的输入重定向运算

将计算表达式输出给bc去执行，特点类似于文件中输入，可以输入多行表达式。更加清晰。

语法：

#第一种方式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var name=`bc [options] &lt;&lt;EOF</span><br><span class="line">第一行表达式</span><br><span class="line">第二行表达式</span><br><span class="line">...</span><br><span class="line">EOF</span><br><span class="line">`</span><br></pre></td></tr></table></figure>

#第二种方式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var name=$(bc [options] &lt;&lt;EOF</span><br><span class="line">第一行表达式</span><br><span class="line">第二行表达式</span><br><span class="line">...</span><br><span class="line">EOF</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

var name这里Shell变量的名字

bc执行bc的命令

EOF..EOF输入流的多行表达式

含义：将EOF中间多行表达式输入给到bc去执行，将bc执行的结果赋值shel变量

【示例】Shell中非互动式的输入重定向运算

![image-20240128192040807](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218216.png)

### 流程控制语句

#### 条件if语句

##### if语句语法格式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">if condition</span><br><span class="line">then</span><br><span class="line">	command1</span><br><span class="line">	command2</span><br><span class="line">	... </span><br><span class="line">	commandN</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

写成一行（适用于终端命令提示符）：

`if 条件;then 命令;fi`

【示例】判断num的值是否是10

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试<span class="keyword">if</span>单分支</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">键盘输入一个数num</span></span><br><span class="line">read -p &quot;请输入一个数：&quot; num</span><br><span class="line">if ((num==10))</span><br><span class="line">then</span><br><span class="line">	echo&quot;您输入的数是10&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

##### if else语句语法格式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">if condition</span><br><span class="line">then</span><br><span class="line">	commadd1</span><br><span class="line">	command2</span><br><span class="line">	...</span><br><span class="line">	commandN</span><br><span class="line">else</span><br><span class="line">	command</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

写成一行（适用于终端命令提示符）：

`if 条件;then 命令;else 命令;fi`

【示例】输入年龄判断是否成人

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试<span class="keyword">if</span> <span class="keyword">else</span></span></span><br><span class="line">read -p&quot;请输入年龄：&quot;age</span><br><span class="line">if ((age&gt;=18))</span><br><span class="line">then</span><br><span class="line">	echo &quot;成年&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;未成年&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

##### if else-if else语法格式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">if condition1</span><br><span class="line">then</span><br><span class="line">	command1</span><br><span class="line">elif codition2</span><br><span class="line">then</span><br><span class="line">	command2</span><br><span class="line">else</span><br><span class="line">	commandN</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>


【示例】输入成绩判断成绩等级

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试<span class="keyword">if</span> <span class="keyword">elif</span> <span class="keyword">else</span> 多分支结构</span></span><br><span class="line">read -p &quot;请输入成绩：&quot; score</span><br><span class="line">if ((score&gt;=90))</span><br><span class="line">then</span><br><span class="line">	echo &quot;成绩等级为A&quot;</span><br><span class="line">elif ((score&gt;=80))</span><br><span class="line">then</span><br><span class="line">	echo &quot;成绩等级为B&quot;</span><br><span class="line">elif ((score&gt;=70))</span><br><span class="line">then</span><br><span class="line">	echo &quot;成绩等级为C”</span><br><span class="line">elif ((score&gt;=60))</span><br><span class="line">then</span><br><span class="line">	echo &quot;成绩及格&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;成绩不及格&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

【示例】根据输入的值判断是周几。如输入1输出”周一“

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">read -p&quot;请输入一个数(1-7)：&quot; num</span><br><span class="line">if [[ $num == 1 ]]</span><br><span class="line">then</span><br><span class="line">	echo &quot;周一&quot;</span><br><span class="line">elif [[ $num == 2 ]]</span><br><span class="line">then</span><br><span class="line">	echo &quot;周二&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

##### 选择嵌套

语法格式

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">if [ condition1 ];then</span><br><span class="line">	command1</span><br><span class="line">	if [ condition2 ];then</span><br><span class="line">		command2</span><br><span class="line">	fi</span><br><span class="line">else</span><br><span class="line">	if [ condition3 ];then</span><br><span class="line">		command3</span><br><span class="line">	elif [ condition4 ];then</span><br><span class="line">		command4</span><br><span class="line">	else</span><br><span class="line">		command5</span><br><span class="line">	fi</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

【示例】输入成绩输出成绩的等级

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="keyword">if</span>条件语句嵌套</span></span><br><span class="line">read -p &quot;请输入成绩：&quot; score</span><br><span class="line">if ((score&gt;0 &amp;&amp; score&lt;=100))</span><br><span class="line">then</span><br><span class="line">	echo &quot;输入的成绩是正确的&quot;</span><br><span class="line">    if ((score&gt;=90))</span><br><span class="line">    then</span><br><span class="line">    	echo &quot;成绩的等级为A&quot;</span><br><span class="line">    elif ((score&gt;=80))</span><br><span class="line">    then</span><br><span class="line">    	echo &quot;成绩的等级为B&quot;</span><br><span class="line">    elif ((score&gt;=70)】</span><br><span class="line">    then</span><br><span class="line">    	echo &quot;成绩的等级为C&quot;</span><br><span class="line">    elif ((score&gt;=60)】</span><br><span class="line">    then</span><br><span class="line">    	echo &quot;及格&quot;</span><br><span class="line">    else</span><br><span class="line">    	echo &quot;不及格&quot;</span><br><span class="line">    fi</span><br><span class="line">else</span><br><span class="line">	echo &quot;偷入的成绩不正确”</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>



#### 内置命令test

Shell中test命令用于检查某个条件是否成立，它可以进行数值、字符串和文件三个方面的测试。功能和一样。

##### 整数比较测试

整数比较语法

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if test 数字1 options 数字2</span><br><span class="line">then</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>


options具体如下：

![image-20240129212756654](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218217.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">test</span>命令检查整数</span></span><br><span class="line">num1=100</span><br><span class="line">num2=200</span><br><span class="line">if test $numl -lt $num2</span><br><span class="line">then</span><br><span class="line">	echo &quot;num1小于num2&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;num1不小于num2&quot;</span><br><span class="line">fi</span><br><span class="line">num3=200</span><br><span class="line">if test $num2 -eq $num3</span><br><span class="line">then</span><br><span class="line">	echo &quot;num2和num3相等&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">-a -o</span></span><br><span class="line">if test $num1 -lt $num2 -a $num2 -eq $num3</span><br><span class="line">then</span><br><span class="line">	echo &quot;两个条件成立&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;两个条件不成立&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

#####  字符串比较测试

![image-20240129213552217](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218218.png)

![image-20240129213616548](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218219.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">test</span>命令检查字符串</span></span><br><span class="line">str1=&quot;hello&quot;</span><br><span class="line">if test -z $str1</span><br><span class="line">then</span><br><span class="line">	echo &quot;str1为空&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;str1不为空&quot;</span><br><span class="line">fi</span><br><span class="line">if test $str1</span><br><span class="line">then</span><br><span class="line">	echo &quot;str1不为空&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;str1为空&quot;</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">str2=&quot;world&quot;</span><br><span class="line">if test $strl = $str2</span><br><span class="line">then</span><br><span class="line">	echo &quot;str1和str2相等&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;不相等&quot;</span><br><span class="line">fi</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">多条件</span></span><br><span class="line">if test $strl -o 1 -eq 1</span><br><span class="line">then</span><br><span class="line">	echo &quot;条件成立&quot;</span><br><span class="line">fi</span><br><span class="line">if test $strl -a 10 -eq 1</span><br><span class="line">then</span><br><span class="line">	echo &quot;条件成立&quot;</span><br><span class="line">else </span><br><span class="line">	echo &quot;条件不成立&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

##### 文件测试

![image-20240129214204828](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218220.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">test</span>检查文件</span></span><br><span class="line">file=&quot;/root/test_shell/test_test1.sh&quot;</span><br><span class="line">if test -e $file</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件存在&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不存在”</span><br><span class="line">fi</span><br><span class="line">if test -r $file</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件可读”</span><br><span class="line">fi</span><br><span class="line">if test -w $file</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件可写&quot;</span><br><span class="line">fi</span><br><span class="line">if test -s $file</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件不为空&quot;</span><br><span class="line">fi</span><br><span class="line">if test -d $sfile</span><br><span class="line">then</span><br><span class="line">	echo &quot;文件是目录&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;文件不是目录&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

test命令经常与`-a`和`-o`一起使用，`&&`和`||`只能使用到`[]`中

【示例】if中有多条件时候，必须都满足才会执行

根据提示输入文件全名和输入写入的数据。判断文件是否有可写权限和输入的数据长度不为0，满足以上2个条件将用户的数据写入到指定的文件中去。

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">read -p &quot;请输入文件名：&quot; filename</span><br><span class="line">read -p &quot;请输入写入的内容：&quot; data</span><br><span class="line">echo &quot;文件名：$filename,内容：$data&quot;</span><br><span class="line">if test -w $filename -a -n $data</span><br><span class="line">then</span><br><span class="line">	echo $data &gt; $filename</span><br><span class="line">	echo &quot;写入内容成功&quot;</span><br><span class="line">else</span><br><span class="line">	echo &quot;写入内容失败&quot;</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>

#### case语句

`case...esac`为多选择语句，与其他语言中的switch...case语句类似，是一种多分枝选择结构，每个case分支用右圆括号`)`开始，用两个分`;;`表示执行结束，跳出整个case...esac语句，esac(就是case反过来)作为结束标记。

可以用case语句匹配一个值与一个模式，如果匹配成功，执行相匹配的命令。

`case...esac`语法格式如下：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">case 值 in</span><br><span class="line">    模式1)</span><br><span class="line">        command1</span><br><span class="line">        command2</span><br><span class="line">        ...</span><br><span class="line">        commandN</span><br><span class="line">    ;;</span><br><span class="line">    模式2)</span><br><span class="line">        command1</span><br><span class="line">        command2</span><br><span class="line">        ...</span><br><span class="line">        commandN</span><br><span class="line">    ;;</span><br><span class="line">esac</span><br></pre></td></tr></table></figure>

case工作方式如上所示，取值后面必须为单词in，每一模式必须以右括号结束。取值可以为变量或常数，匹配发现取值符合某一模式后，其间所有命令开始执行直至`;;`。

取值将检测匹配的每一个模式。一旦模式匹配，则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式，使用星号`*`捕获该值，再执行后面的命令。

case、in和esac都是Shell关键字，esac就是case的反写在这里代表结束case。

匹配模式：可以是一个数字、一个字符串，甚至是一个简单正则表达式。

简单正则表达式支持如下通配符：

![image-20240129215703726](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218221.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="keyword">case</span>多分支选择结构</span></span><br><span class="line">read -p &quot;请输入一个(0-7)之间的数：&quot; num</span><br><span class="line">case $num in</span><br><span class="line">	1)</span><br><span class="line">		echo &quot;周一&quot;</span><br><span class="line">		;;</span><br><span class="line">	2)</span><br><span class="line">		echo &quot;周二&quot;</span><br><span class="line">		;;</span><br><span class="line">	3)</span><br><span class="line">		echo &quot;周三&quot;</span><br><span class="line">		;;</span><br><span class="line">	4)</span><br><span class="line">		echo &quot;周四&quot;</span><br><span class="line">		;;</span><br><span class="line">	5)</span><br><span class="line">		echo &quot;周五&quot;</span><br><span class="line">		;;</span><br><span class="line">	6)</span><br><span class="line">		echo &quot;周六&quot;</span><br><span class="line">		;;</span><br><span class="line">	0|7)</span><br><span class="line">		echo &quot;周日&quot;</span><br><span class="line">		;;</span><br><span class="line">	*)</span><br><span class="line">		echo &quot;输入有误&quot;</span><br><span class="line">		;;</span><br><span class="line">esac		</span><br></pre></td></tr></table></figure>



<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="keyword">case</span>多分支结构</span></span><br><span class="line">case $1 in</span><br><span class="line">	start | S)</span><br><span class="line">		echo &quot;启动成功&quot;</span><br><span class="line">		;;</span><br><span class="line">	stop | T)</span><br><span class="line">		echo &quot;停止成功&quot;</span><br><span class="line">		;;</span><br><span class="line">	restart | R)</span><br><span class="line">		echo &quot;重新启动成功&quot;</span><br><span class="line">		;;</span><br><span class="line">	*)</span><br><span class="line">		echo &quot;输入有误&quot;</span><br><span class="line">		;;</span><br><span class="line">esac</span><br></pre></td></tr></table></figure>

![image-20240129220547110](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202401292218222.png)

#### while语句

##### while循环

while循环用于不断执行一系列命令，也用于从输入文件中读取数据。其语法格式为：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">while condition</span><br><span class="line">do</span><br><span class="line">	command</span><br><span class="line">done</span><br></pre></td></tr></table></figure>



<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="keyword">while</span>循环</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">键盘输入一个数</span></span><br><span class="line">read -p &quot;请输入一个整数：&quot; num</span><br><span class="line">i=1</span><br><span class="line">while ((i&lt;=num))</span><br><span class="line">do</span><br><span class="line">	echo&quot;当前i的值：$i&quot;</span><br><span class="line">	let i++</span><br><span class="line">done</span><br></pre></td></tr></table></figure>



<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">使用whi1e循环求1-100的和</span></span><br><span class="line">i=1</span><br><span class="line">sum=0</span><br><span class="line">while ((i&lt;=100))</span><br><span class="line">do</span><br><span class="line">	sum=$((sum+i))</span><br><span class="line"><span class="meta prompt_">	#</span><span class="language-bash"><span class="built_in">sum</span>=`<span class="built_in">expr</span> <span class="variable">$sum</span> + <span class="variable">$i</span>`</span></span><br><span class="line"><span class="meta prompt_">	#</span><span class="language-bash"><span class="built_in">sum</span>=$((<span class="variable">$sum</span>+<span class="variable">$i</span>))</span></span><br><span class="line">	let i++</span><br><span class="line">done</span><br><span class="line">echo &quot;sum: $sum&quot; </span><br></pre></td></tr></table></figure>



##### 无限循环

无限循环语法格式：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">while:</span><br><span class="line">do</span><br><span class="line">	command</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

或

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">while true</span><br><span class="line">do</span><br><span class="line">	command</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

![image-20240130154742282](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032034453.png)

![image-20240130154802584](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032035634.png)

##### 跳出循环

在循环过程中，有时候需要在未达到循环结束条件时强制跳出循环，Shell使用两个命令来实现该功能：break和continue

**break命令**

break命令允许跳出当前整个循环。

【示例】break命令退出当前循环，脚本进入死循环直至用户输入数字大于5。要跳出这个循环

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">退出循环<span class="built_in">break</span>的使用</span></span><br><span class="line">while true</span><br><span class="line">do</span><br><span class="line">	read -p &quot;请输入一个整数：&quot; num</span><br><span class="line">	case $num in</span><br><span class="line">		1|2|3|4|5)</span><br><span class="line">			echo &quot;您输入的数：$num&quot;</span><br><span class="line">			;;</span><br><span class="line">		*)</span><br><span class="line">			echo &quot;您输入的数不是1 2 3 4 5，退出循环&quot;</span><br><span class="line">			break</span><br><span class="line">			;;</span><br><span class="line">	esac</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

**continue命令**

continue命令允许跳出本次循环。

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试退出循坏<span class="built_in">continue</span></span></span><br><span class="line">while</span><br><span class="line">do</span><br><span class="line">	read -p &quot;请输入一个数：&quot; num</span><br><span class="line">	if ((num==1 || num==2 || num==3 || num==4 || num==5))</span><br><span class="line">	then</span><br><span class="line">		echo &quot;您输入的数是：$num&quot;</span><br><span class="line">	else</span><br><span class="line">		echo &quot;您输入的数不是1 2 3 4 5&quot;</span><br><span class="line">		continue</span><br><span class="line">		echo&quot;continue退出本次循环&quot;</span><br><span class="line">	fi</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

#### until语句

until循环执行一系列命令直至条件为true时停止。until循环与while循环在处理方式上刚好相反。

一般while循环优于until循环，但在某些时候一也只是极少数情况下，until循环更加有用。

until语法格式：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">until condition</span><br><span class="line">do</span><br><span class="line">	command</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

condition一般为条件表达式，如果返回值为false，则继续执行循环体内的语句，否则跳出循环。

【示例】使用until命令来输出0~9的数字

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试until循坏</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">输出0-9的数</span></span><br><span class="line">i=0</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">until [[ ! <span class="variable">$i</span> -le 9 ]]</span></span><br><span class="line">until ((i&gt;9))</span><br><span class="line">do</span><br><span class="line">	echo &quot;当前i的值：$i&quot;</span><br><span class="line">	let i++</span><br><span class="line">done</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">计算1-100之间的和</span></span><br><span class="line">i=1</span><br><span class="line">sum=0</span><br><span class="line">until ((i&gt;100))</span><br><span class="line">do</span><br><span class="line">	sum=$((i+sum))</span><br><span class="line">	let i++</span><br><span class="line">done</span><br><span class="line">echo &quot;1-100的和：$sum&quot;</span><br></pre></td></tr></table></figure>

#### for语句

##### 循环第一种方式

与其他编程语言类似，Shell支持for循环。

for循环一般格式为：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">for var in item1 item2 ... itemN</span><br><span class="line">do</span><br><span class="line">	command1</span><br><span class="line">	command2</span><br><span class="line">	commandN</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

写成一行：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">for var in item1 item2 ... itemN;do command1;command2... done;</span><br></pre></td></tr></table></figure>

【示例】for循环顺序输出当前列表中的数字

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="keyword">for</span>循环 <span class="keyword">for</span> <span class="keyword">in</span></span></span><br><span class="line">for i in 1 2 3 10 20 30</span><br><span class="line">do</span><br><span class="line">	echo &quot;当前变量的值：$i&quot;</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">for v in hello bai d com baizhai</span><br><span class="line">do</span><br><span class="line">	echo &quot;当前变量的值：$v&quot;</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

##### 循环第二种方式

语法：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">for var in &#123;start..end&#125;</span><br><span class="line">do</span><br><span class="line">	命令</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

start：循环范围的起始值必须为整数

end：循环范围的结束值，必须为整数

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">输出1-10的整数</span></span><br><span class="line">for i in &#123;1..10&#125;</span><br><span class="line">do</span><br><span class="line">	echo &quot;当前整数：$i&quot;</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">sum=0</span><br><span class="line">for i in &#123;1..100&#125;</span><br><span class="line">do</span><br><span class="line">	sum=$((sum+i))</span><br><span class="line">done</span><br><span class="line">echo &quot;1-100的和：$sum&quot;</span><br></pre></td></tr></table></figure>

##### 循环第三种方式

语法：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">for((i=start;i&lt;=end;i++))</span><br><span class="line">do</span><br><span class="line">	命令</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

一行写法：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">for(i=start;i&lt;=end;i++);do 命令;done</span><br></pre></td></tr></table></figure>



<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">使用<span class="keyword">for</span>循环输出10-20之间的数</span></span><br><span class="line">for((i=10;i&lt;=20;i++))</span><br><span class="line">do</span><br><span class="line">	echo &quot;当前i的值：$i&quot;</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

##### for循环的无限循环

for循环的无限循环语法：

`for((;;));do 命令;done`

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="keyword">for</span>无限循环</span></span><br><span class="line">i=1</span><br><span class="line">for((;;))</span><br><span class="line">do</span><br><span class="line">	if((i==5))</span><br><span class="line">	then</span><br><span class="line">		echo &quot;i等于5退出循环&quot;</span><br><span class="line">		break</span><br><span class="line">	else</span><br><span class="line">		echo &quot;当前i的值：$i&quot;</span><br><span class="line">		let i++</span><br><span class="line">fi</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

#### select语句

select in循环用于增强交互性，它可以显示出带编号的菜单，用于输入不同的编号就可以选择不同的菜单，并执行不同的功能，select in是Shell独有的一种循环，非常适合终端这样的交互场景，其它语言没有。

语法格式如下：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">select var in 菜单1 菜单2 ...</span><br><span class="line">do</span><br><span class="line">	命令</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

注意：select是无限循环（死循环），输入空值，或者输入的值无效，都不会结束循环，只有遇到break语句，或者按下Ctrl+D组合键才能结束循环。

执行命令中终端输出`#?`代表可以输入选择的菜单编号

 【示例】select in的使用

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">测试select语句的使用</span></span><br><span class="line">echo &quot;一年四个季节，您最喜欢哪个季节？&quot;</span><br><span class="line">select d in &quot;春大&quot; &quot;夏天&quot; &quot;秋大&quot; &quot;冬天&quot;</span><br><span class="line">do</span><br><span class="line">	echo &quot;您最喜欢的季节是：$d&quot;</span><br><span class="line">	break</span><br><span class="line">done</span><br></pre></td></tr></table></figure>

![image-20240201162643067](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032046256.png)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">select语句与<span class="keyword">case</span>一起使用</span></span><br><span class="line">echo &quot;您最喜欢的老师是哪位？&quot;</span><br><span class="line">select t in 张老师 李老师 王老师 赵老师</span><br><span class="line">do</span><br><span class="line">	case $t in</span><br><span class="line">		&quot;张老师&quot;)</span><br><span class="line">			echo &quot;您最喜欢的老师是张老师&quot;</span><br><span class="line">			break</span><br><span class="line">			;;</span><br><span class="line">		&quot;李老师&quot;)</span><br><span class="line">			echo &quot;您最喜欢的老师是李老师&quot;</span><br><span class="line">			break</span><br><span class="line">			;;</span><br><span class="line">		&quot;赵老师&quot;)I</span><br><span class="line">			echo &quot;您最喜欢的老师是赵老师&quot;</span><br><span class="line">			break</span><br><span class="line">			;;</span><br><span class="line">		&quot;王老师&quot;)</span><br><span class="line">			echo &quot;您最喜欢的老师是王老师&quot;</span><br><span class="line">			break</span><br><span class="line">			;;</span><br><span class="line">	esac</span><br><span class="line">done</span><br></pre></td></tr></table></figure>



![image-20240201162612012](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032046522.png)

### Shell函数

Shell函数和其他编程语言一样，函数是由若干条Shell命令组成的语句块，实现Shell脚本代码重用和模块化编程。

#### 系统函数

#####  basename

basename返回完整路径最后/的部分，常用于获取文件名，基本语法如下：

`basename [pathname] [suffix]`

suffix为后缀，如果suffix被指定了，basename会将pathname或string中的suffix去掉。

【示例】basename的使用

![image-20240201163354799](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032046408.png)

【示例】basename的使用（写入到脚本文件）

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">系统函数<span class="built_in">basename</span></span></span><br><span class="line">filename1=`basename /root/test_shell/test_while.sh`</span><br><span class="line">filename2=$(basename /root/test_shell/test_while.sh .sh)</span><br><span class="line">echo &quot;filenamel:$filename1&quot;</span><br><span class="line">echo &quot;filename2:$filename2&quot;</span><br></pre></td></tr></table></figure>

##### dirname

dirname返回完整路径最后V的前面的部分，常用于返回路径部分。

dirname文件绝对路径（功能描述：从给定的包含绝对路径的文件名中去除文件名（非目录的部分)，然后返回剩下的路径（目录的部分）)

【示例】dirname的使用

![image-20240201163823760](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032047339.png)

【示例】dirname的使用（写到脚本中）

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">dirname</span>系统函数</span></span><br><span class="line">filename=`basename /root/test_shell/test_while.sh`</span><br><span class="line">mydire=$(dirname /root/test_shell/test_while.sh)</span><br><span class="line">echo &quot;文件名：$filename&quot;</span><br><span class="line">echo &quot;文件路径：$mydire&quot;</span><br></pre></td></tr></table></figure>

#### 自定义函数

##### 函数定义

shell中函数的定义格式如下：

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[ function ] funname [()]</span><br><span class="line">&#123;</span><br><span class="line">	action;</span><br><span class="line">	[return int;]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

说明：

1. 可以带function fun()定义，也可以直接fun()定义，不带任何参数。
2. 参数返回，可以显示加：return返回，如果不加，将以最后一条命令运行结果，作为返回值。return后跟数值n(0-255)

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">自定义函数</span></span><br><span class="line">function test_fun1()&#123;</span><br><span class="line">	echo &quot;自定义函数fun1&quot;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">调用函数之前必须先定义好函数</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="built_in">test</span> fun2</span></span><br><span class="line"></span><br><span class="line">test fun2()&#123;</span><br><span class="line">	echo &quot;自定义函数fun2&quot;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">调用函数</span></span><br><span class="line">test_fun1</span><br><span class="line">test_fun2</span><br></pre></td></tr></table></figure>

【示例】函数示例（有返回值）

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">定义函数，有返回值</span></span><br><span class="line">test_add()&#123;</span><br><span class="line"><span class="meta prompt_">	# </span><span class="language-bash">键盘输入两个整数</span></span><br><span class="line">	read -p &quot;请输入第一个整数：&quot; num1</span><br><span class="line">	read -p &quot;请输入第二个整数：&quot; num2</span><br><span class="line">	return $((num1+num2))</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">调用函数</span></span><br><span class="line">test_add</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取函数的返回值</span></span><br><span class="line">echo &quot;函数的返回值：$?&quot;</span><br></pre></td></tr></table></figure>

函数返回值在调用该函数后通过`$?`来获得。

注意：**所有函数在使用前必须定义**。这意味着必须将函数放在脚本开始部分，直至shell解释器首次发现它时，才可以使用。调用函数仅使用其函数名即可。

##### 函数参数

在Shell中，调用函数时可以向其传递参数。在函数体内部，通过`$n`的形式来获取参数的值，例如，`$1`表示第一个参数，`$2`表示第二个参数...

注意，`$10`不能获取第十个参数，获取第十个参数需要`$&#123;10&#125;`。当n>=10时，需要使用`$&#123;n&#125;`来获取参数。

【示例】函数参数的使用

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">定义函数传递函数参数</span></span><br><span class="line">test_param()&#123;</span><br><span class="line">	echo &quot;第一个参数：$1&quot;</span><br><span class="line">	echo &quot;第二个参数：$2&quot;</span><br><span class="line">	echo &quot;第三个参数：$3&quot;</span><br><span class="line">	echo &quot;第10个参数：$&#123;10&#125;&quot;</span><br><span class="line">	echo &quot;第11个参数：$&#123;11&#125;&quot;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">调用函数</span></span><br><span class="line">test_param 1 2 3 4 5 6 7 8 9 100 101 102</span><br></pre></td></tr></table></figure>

【示例】定义函数绘制图像

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">定义函数及<span class="keyword">for</span>循环综合练习</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">输出一个矩形</span></span><br><span class="line">echo &quot;输出一个矩形&quot;</span><br><span class="line">test_fun1()&#123;</span><br><span class="line">	for i in &#123;1..5&#125;</span><br><span class="line">	do</span><br><span class="line">		echo &quot;***&quot;</span><br><span class="line">	done</span><br><span class="line">&#125;	</span><br><span class="line">test_fun1</span><br><span class="line"></span><br><span class="line">echo &#x27;输出一个矩形2&#x27;</span><br><span class="line">test_fun2()&#123;</span><br><span class="line">	for((i=1;i&lt;=6;i++))</span><br><span class="line">	do</span><br><span class="line">		for((j=1;j&lt;=4;j++))</span><br><span class="line">		do</span><br><span class="line">			echo -n &quot;*&quot;</span><br><span class="line">		done</span><br><span class="line">		echo  # 输出换行</span><br><span class="line">	done</span><br><span class="line">&#125;</span><br><span class="line">test_fun2</span><br><span class="line"></span><br><span class="line">echo &quot;输出直角三角形”</span><br><span class="line">test_fun3()&#123;</span><br><span class="line">	for((i=1;i&lt;=5;i++))</span><br><span class="line">	do</span><br><span class="line">		for((j=1;j&lt;=$i;j++))</span><br><span class="line">		do</span><br><span class="line">			echo -n &quot;*&quot;</span><br><span class="line">		done</span><br><span class="line">		echo</span><br><span class="line">	done</span><br><span class="line">&#125;</span><br><span class="line">test_fun3</span><br></pre></td></tr></table></figure>

![image-20240201165737019](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032047819.png)

#####  Shell程序与函数的区别

函数和Shell程序比较相似，区别在于：

Shell程序（内置命令和外部脚本文件），外部脚本文件是在子Shell中运行，会开启独立的进程运行。

Shell函数在当前Shell的进程中运行。

【示例】Shel程序与函数的区别

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">test_fun()&#123;</span><br><span class="line">echo &quot;函数中输出：进程ID$$&quot;</span><br><span class="line">&#125;</span><br><span class="line">test_fun</span><br><span class="line">echo &quot;脚本文件中：进程ID$$&quot;</span><br></pre></td></tr></table></figure>

![image-20240201170221887](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032047632.png)

### Shell重定向输入输出

#### 概念

##### 标准输入

从键盘读取用户输入的数据，然后再把数据拿到Shell程序中使用。

##### 标准输出

Shell程序产生的数据，这些数据一般都是呈现到显示器上供用户浏览查看

##### 输入输出重定向

输入方向就是数据从哪里流向程序。数据默认从键盘流向程序，如果改变了它的方向，数据就从其它地方流入，这就是输入重定向。

输出方向就是数据从程序流向哪里。数据默认从程序流向显示器，如果改变了它的方向，数据就流向其它地方，这就是输出重定向。

#### 文件描述符

linux命令默认从标准输入设备(stdin)获取输入，将结果输出到标准输出设备(stdout)显示。一般情况下，标准输入设备就是键盘，标准输出设备就是终端，即显示器。

在linux shell执行命令时，每个进程都和三个打开的文件相联系，并使用文件描述符来引用这些文件。由于文件描述符不容易记忆，shell同时也给出了相应的文件名。

![image-20240201170613166](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032056153.png)

#### 重定向命令列表

![image-20240201170850153](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032056229.png)

##### 输出重定向

![image-20240201170826698](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032056594.png)

![image-20240201171043019](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032056377.png)

![image-20240201171347044](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057655.png)

##### 输入重定向

wC命令可以用来对文本进行统计，包括单词个数、行数、字节数。

wc语法格式：

`wc [options] [文件名]`

options有如下：

![image-20240201171621618](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057589.png)

![image-20240201171659676](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057891.png)

【示例】读取文件每行内容

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">输入重定间</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">读取文件内容</span></span><br><span class="line">r=1</span><br><span class="line">while read m</span><br><span class="line">do</span><br><span class="line">	echo&quot;第$r行，内容是：$m&quot;</span><br><span class="line">	let r++</span><br><span class="line">done &lt; log.txt</span><br></pre></td></tr></table></figure>

【示例】标记位读取内容

![image-20240201172106448](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057992.png)

### 文本处理工具

#### grep文本搜索

grep是一种强大的文本搜索工具，用于根据关键字进行行过滤，并把匹配的行打印出来。

grep语法格式：

`grep [选项] '关键字' 文件名`

它在一个或多个文件中搜索满足模式的文本行。

常用的grep选项：

![image-20240201172322202](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057131.png)

![image-20240203100250887](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041145935.png)



![image-20240203100642812](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057445.png)

![image-20240203100718496](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057552.png)

![image-20240203100842828](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032057757.png)

![image-20240203100940561](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058503.png)

![image-20240203101007811](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058498.png)

![image-20240203101033123](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058513.png)

![image-20240203101429736](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058888.png)

#### cut按列切分文本

cut译为“剪切、切割”，是一个强大文本处理工具，它可以将文本按列进行划分的文本处理。cut命令逐行读入文本，然后按列划分字段并进行提取、输出等操作。

语法格式：

`cut [options] 文件名`

options参数说明

![image-20240203101606240](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058526.png)

**提取范围说明**

![image-20240203101648085](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058493.png)

【示例】cut的使用

 准备test_cut.xt文件内容

![image-20240203101841005](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058376.png)

【示例】cut截取列数据

![image-20240203101954943](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058217.png)

![image-20240203102100439](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041147383.png)

【示例】cut按字符提取

![image-20240203102419788](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058554.png)

![image-20240203102450789](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058701.png)

![image-20240203102654486](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058545.png)

【示例】cut的切割获取指定单词

![image-20240203102912665](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058329.png)

【示例】cut的切割bash进程的PID号

![image-20240203103014436](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032058144.png)

【示例】cut的切割当前服务器的IP

![image-20240203103108093](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059055.png)

#### sed文本编辑器

sed是Liux下一款功能强大的非交互流式文本编辑器，可以对文本文件进行增、删改、查等操作，支持按行、按字段、按正则匹配文本内容，灵活方便，特别适合于大文件的编辑。

sed工作原理：sed会读取每一行数据到模式空间中，判断当前行是否符合模式心配要求，符合要求就会执行sed程序命令，否则不会执行sed程序命令，如果不写四配模式，那么每一行都会执行sed程序命令。

sed的使用语法：

`sed [选项参数] [模式匹配 | sed程序命令] [文件名]`

sed的常用选项：

![image-20240203103614821](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059966.png)

![image-20240203103729930](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059899.png)

##### 【示例】向文件中添加或插入行

1.准备test_sed.txt内容

2.`sed '3aworld' test_sed.txt`      #向第三行后面添加world，3表示行号

![image-20240203104025459](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059854.png)

注意：预览可以看到是添加了，但实际没有添加到文件内容。想要真是的添加到文件，需要加选项 `-i`。

![image-20240203104114124](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059368.png)



![image-20240203104257274](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059467.png)

![image-20240203104426376](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059522.png)

![image-20240203104522105](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059686.png)

##### 【示例】更改文件中指定的行

![image-20240203104708214](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041150896.png)

![image-20240203104822114](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059659.png)

##### 【示例】删除文件中的行

![image-20240203104914682](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059198.png)

![image-20240203105915529](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041227856.png)

2.删除3~5之外的所有行

![image-20240203112354974](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059651.png)

3.删除从匹配abc的行到最后一行

![image-20240203112604351](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041227997.png)

4.删除空行

![image-20240203113044347](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059106.png)

5.删除不匹配hello或abc的行，`/hello\|abc/`表示匹配hello或abc，`!`表示取反

![image-20240203113326358](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059920.png)

6.删除`1~3`行中，匹配内容hello的行，1,3表示匹配`1~3`行，`&#123;/hello/d&#125;`表示删除匹配hello的行

![image-20240203113512409](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059036.png)

#####  【示例】替换文件中的内容

1.将文件中的a替换为123，默认只替换每行第一个123

![image-20240203114041506](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041228304.png)

![image-20240203114130143](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032059725.png)

![image-20240203114235556](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032100200.png)

4.将每行中所有匹配的a替换为123，并将替换后的内容写入test_sed2.txt

![image-20240203114411504](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032100447.png)

![image-20240203114550942](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032100381.png)

5.匹配有#号的行，替换匹配行中逗号后的所有内容为空`(,.*)`表示逗号后的所有内容

​	![image-20240203114715692](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032100517.png)

6.替换每行中的最后两个字符为空，每个点代表一个字符，`$`表示匹配末尾`(...$)`表示匹配最后两个字符 

![image-20240203114950448](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032100562.png)

7.在test_sed.txt文件的每一行后面加上"hahha"字段

![image-20240203115023685](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032100585.png)

##### 【示例】打印文件中的行

1.打印文件中的第三行内容

![image-20240203115325660](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032100507.png)

2.从第一行开始，每隔两行打印一行，波浪号后面的2表示步长

![image-20240203115508010](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101863.png)

3.打印文件的最后一行

![image-20240203115338000](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101427.png)

4.打印1-3行

![image-20240203115345629](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101023.png)

5.打印匹配的行

![image-20240203115634612](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101129.png)

##### 【示例】打印文件的行号

1.打印test sed.txt文件最后一行的行号

![image-20240203120027153](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101631.png)

2.打印匹配abc的行的行号

![image-20240203115903879](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101564.png)

3.打印空行行号

![image-20240203115853510](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101509.png)

##### 【示例】从文件中读取内容

1.将文件test_sed3.txt中的内容，读入test_sed4.txt中，会在test_sed4.txt中的**每一行**后都读入test_sed3.txt的内容

![image-20240203120234360](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101344.png)

2.在test_sed.3.txt的第3行之后插入文件test_sed4.txt的内容（可用于向文件中插入内容)

![image-20240203120356379](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101635.png)

3.在匹配456的行之后插入文件test_sed4.txt的内容，如果test_sed3.txt中有多行匹配456则在每一行之后都会插入

![image-20240203120518338](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101391.png)

4.在test_sed3.txt的最后一行插入test_sed4.txt的内容

![image-20240203120656179](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101346.png)

##### 【示例】向文件中写入内容

1.将test_sed3.txt文件的内容写入test_sed4.txt文件，如果test_sed3.txt文件不存在则创建，如果test_sed.4.txt存在则覆盖之前的内容

![image-20240203120846835](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032101428.png)

2.将文件test_sed3.txt中的第2行内容写入到文件test_sed4.txt

![image-20240203120958428](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102451.png)

3.将test_sed3.txt的第2行和最后一行内容写入test_sed4.txt

![image-20240203121202820](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102166.png)

-e： 它告诉sed将下一个参数解释为一个sed指令，只有当命令行上给出多个sed指令时才需要使用-e选项



4.将test_sed3.txt的第2行和最后一行内容分别写入test_sed4.txt和test_sed5.txt中

![image-20240203121409496](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102258.png)

5.将test_sed3.txt中匹配789或123的行的内容，写入到test_sed4.txt中

![image-20240203121559874](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102030.png)

6.将test_sed.3.txt中从匹配123的行到最后行的内容，写入到test_sed.4.txt中

`,$`：到最后一行

![image-20240203121841438](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102956.png)

7.将test_sed3.txt中从匹配456的行及其后2行的内容，写入到test_sed4.txt中

![image-20240203121919344](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102573.png)

#### awk文本分析工具

##### awk概述

awk是一种强大的文本分析工具，主要用于在linux/uniⅸ下对文本和数据进行处理。对数据进行分析、统计并生成报表，比如网站的访问量，访问的IP量等等。

awk是种编程语言，awk可以定义变量、运算符，使用流程控制语句进行深度加工与分析。

awk其名称得自于它的创始人Alfred Aho、Peter Weinberger和Brian Kernighan姓氏的首个字母。

awk的处理文本和数据的方式：把文件逐行读入，以空格为默认分隔符将每行切片。切片的部分再进行各种分析处理。

##### awk基本使用

使用方法：

`awk 选项 '命令部分' 文件名`

特别说明：引用shell变量需用双引号引起

常用命令选项

![image-20240203123414316](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032032231.png)

AWK内置变量

![image-20240203123457651](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102570.png)

![image-20240203124203929](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032102006.png)

【示例】awk匹配内容整行输出，默认每行空格切割数据，并将这行赋给内部变量$0

![image-20240203132304618](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031333107.png)

【示例】awk匹配以root开头的行

![image-20240203132313537](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031333108.png)

【示例】awk使用一行作为输入，默认每行空格切割数据，并将这行赋给内部变量$0

![image-20240203132538803](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031333109.png)

![image-20240203132644186](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031333110.png)

##### 格式化输出print和printf

print函数：类似echo，它是**换行输出**

printf函数：类似echo-n，它**不换行输出**，可以使用%s、%d进行占位。其中%s表示字符类型，%d数值类型。

`-`：表示左对齐，默认是右对齐

例如：`%-15s`                 表示所占15字符，使用左对齐方式显示。

【示例】print的使用

![image-20240203133124844](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032103185.png)

【示例】printf占位的使用

![image-20240203133232646](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031333112.png)

![image-20240203133313710](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031337593.png)

![image-20240203133422718](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031337594.png)



【示例】print打印文件每行属性信息

统计passwd文件名，每行的行号，每行的列数，对应的完整行内容

![image-20240203133630224](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031337595.png)

![image-20240203133722927](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031337596.png)

【示例】打印第三行信息

![image-20240203133906367](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633788.png)

##### awk中BEGIN...END使用

BEGIN：表示在程序开始前执行

END：表示所有文件处理完后执行

用法：`'BEGIN&#123;开始处理之前&#125;;&#123;处理中&#125;;END&#123;处理结束后&#125;'`

【示例】添加开始与结束内容

![image-20240203134419835](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633789.png)

![image-20240203134541005](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633790.png)

![image-20240203134628718](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633791.png)

##### awk变量定义

【示例】-v定义变量

![image-20240203134922839](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633792.png)

##### awk中流程控制语句

![image-20240203135427288](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633793.png)

1. if语句语法格式
   `&#123; if(表达式) &#123;语句1;语句2;...&#125; &#125;`
   准备test_awk.txt文件 

   ![image-20240203135709752](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633794.png)

   ![image-20240203135846364](https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633795.png)

2. if else的语法格式

   `&#123;if(表达式) &#123;语句;语句;...&#125; else&#123;语句;语句;...&#125;&#125;</code></p>
<p>   【示例】awk中使用<code>if...else</code></p>
<p>   <img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633796.png" alt="image-20240203140139314"></p>
<p>   <img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633797.png" alt="image-20240203140233114"></p>
<ol>
<li><p>if else if else if的语法格式</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;if(表达式1)&#123;语句；语句；...&#125;</span><br><span class="line">else if(表达式2)&#123;语句;语句; ...&#125;</span><br><span class="line">else if(表达式3)&#123;语句;语句; ...&#125;</span><br><span class="line">else&#123;语句;语句; ...&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>​    <img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633798.png" alt="image-20240203140608122"></p>
</li>
</ol>
<h5 id="awk中循环语句的使用"><a href="#awk中循环语句的使用" class="headerlink" title="awk中循环语句的使用"></a>awk中循环语句的使用</h5><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633799.png" alt="image-20240203140922700"></p>
<p>【示例】使用循环拼接字符串</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633800.png" alt="image-20240203141109009"></p>
<p>【示例】使用循环计算每行的和</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633801.png" alt="image-20240203141355571"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633802.png" alt="image-20240203141604923"></p>
<p>【示例】循环中使用break</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633803.png" alt="image-20240203141827328"></p>
<p> 【示例】操指定数字运算</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633804.png" alt="image-20240203141931217"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633805.png" alt="image-20240203142020130"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633806.png" alt="image-20240203142120705"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633807.png" alt="image-20240203142646024"></p>
<p>【示例】切割ip</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633808.png" alt="image-20240203143237774"></p>
<p>【示例】显示空行行号</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633809.png" alt="image-20240203143400833"></p>
<h4 id="sort"><a href="#sort" class="headerlink" title="sort"></a>sort</h4><p>sort命令以行为单位对文本进行排序。sort将文件的每一行作为一个单位，相互比较，比较原则是从首字符向后，依次按ASCII码值进行比较，最后将他们按升序输出。</p>
<h5 id="【示例】sort的使用"><a href="#【示例】sort的使用" class="headerlink" title="【示例】sort的使用"></a>【示例】sort的使用</h5><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633810.png" alt="image-20240203143642200"></p>
<h5 id="【示例】sort的-u选项"><a href="#【示例】sort的-u选项" class="headerlink" title="【示例】sort的-u选项"></a>【示例】sort的<code>-u</code>选项</h5><p>在输出行中去除重复行。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633811.png" alt="image-20240203143815597"></p>
<h5 id="【示例】sort的-r选项"><a href="#【示例】sort的-r选项" class="headerlink" title="【示例】sort的-r选项"></a>【示例】sort的<code>-r</code>选项</h5><p>sort默认的排序方式是升序，如果想改成降序，就加个<code>-r</code>就搞定了。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633812.png" alt="image-20240203143917563"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633813.png" alt="image-20240203143939226"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633814.png" alt="image-20240203144003364"></p>
<h5 id="【示例】sort的-o选项"><a href="#【示例】sort的-o选项" class="headerlink" title="【示例】sort的-o选项"></a>【示例】sort的-o选项</h5><p>由于sort默认是把结果输出到标准输出，所以需要用重定向才能将结果写入文件，形如 <code>sort filename &gt; newfile</code>,</p>
<p>但是，如果你想把排序结果输出到原文件中，用重定向可就不行了。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633815.png" alt="image-20240203144150945"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633816.png" alt="image-20240203144302692"></p>
<h5 id="【示例】sort的-n选项"><a href="#【示例】sort的-n选项" class="headerlink" title="【示例】sort的-n选项"></a>【示例】sort的<code>-n</code>选项</h5><p>对数字排序，会出现一种现象，如10比2小的情况。出现这种情况是由于排序程序将这些数字按字符来排序了，排序程序会先比较1和2，显然1小，所以就将10放在2前面。这也是sort的一贯作风。</p>
<p>如果想改变这种现状，就要使用<code>-n</code>选项，“要以数值来排序”！</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633817.png" alt="image-20240203144525158"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633818.png" alt="image-20240203144609321"></p>
<h5 id="【示例】sort的-t选项和-k选项"><a href="#【示例】sort的-t选项和-k选项" class="headerlink" title="【示例】sort的-t选项和-k选项"></a>【示例】sort的<code>-t</code>选项和<code>-k</code>选项</h5><p><code>-t</code>选项，后面可以设定间隔符。</p>
<p><code>-k</code>选项，分割后用来指定列数了。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633819.png" alt="image-20240203144805814"></p>
<p>这个文件有三列，列与列之间用冒号隔开了，第一列表示水果类型，第二列表示水果数量，第三列表示水果价格。</p>
<p>现在想以水果数量来排序，也就是以第二列来排序，如何利用sort实现？</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633820.png" alt="image-20240203144931438"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633821.png" alt="image-20240203145022617"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633822.png" alt="image-20240203145603508"></p>
<h4 id="tee"><a href="#tee" class="headerlink" title="tee"></a>tee</h4><p>tee命令作用把输出的一个副本输送到标准输出，另一个副本拷贝到相应的文件中。如果希望在看到输出的同时，也将其存入一个文件，那么这个命令再合适不过了。</p>
<p> 它的使用语法格式：</p>
<p><code>tee [-a] files</code></p>
<p>其中，-a表示追加到文件末尾。</p>
<p>当执行某些命令或脚本时，如果希望把输出保存下来，tee命令非常方便。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633823.png" alt="image-20240203150829903"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633824.png" alt="image-20240203150926614"></p>
<p><code>&gt;/dev/null</code>：不显示在屏幕上</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031633825.png" alt="image-20240203151113026"></p>
<h4 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h4><h5 id="批量修改文件"><a href="#批量修改文件" class="headerlink" title="批量修改文件"></a>批量修改文件</h5><p>将某目录下.txt文件全部修改为.bat。</p>
<p>1.批量创建文件</p>
<p><code>mkdir test_filedir</code></p>
<p><code>touch test_filedir/file&#123;1...10).txt</code></p>
<p>2.重命名文件语法</p>
<p><code>rename 旧文件名 新文件名 旧文件所在位置</code></p>
<p>注意：旧文件所在位置后面加<code>/*</code>     例如：<code>/root/test filedir/*</code>s</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">批量修改文件</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取所有要修收的文件</span></span><br><span class="line">filenames=$(ls /root/test_shell/test_filedir | grep &#x27;txt&#x27;)</span><br><span class="line">for fname in $filenames</span><br><span class="line">do</span><br><span class="line">	echo&quot;文件名：&quot;$fname</span><br><span class="line">	newname=$(basename $fname .txt)&quot;.bat&quot;</span><br><span class="line">	echo &quot;新文件名：&quot;$newname</span><br><span class="line">	rename $fname $newname /root/test_shell/test_filedir/*</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<h5 id="批量创建用户"><a href="#批量创建用户" class="headerlink" title="批量创建用户"></a>批量创建用户</h5><p>添加用户的命令</p>
<p><code>useradd 用户名</code></p>
<p>给用户设置默认密码</p>
<p><code>echo &quot;123456&quot; | passwd-stdin 用户名</code></p>
<p>【示例】批量添加用户</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031806643.png" alt="image-20240203171544440"></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">批量创建用户</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">获取文件中要添加的所有用户名</span></span><br><span class="line">users=$(cat /root/test_shell/test_adduser.txt)</span><br><span class="line">for u in $users</span><br><span class="line">do</span><br><span class="line"><span class="meta prompt_">	# </span><span class="language-bash"><span class="built_in">echo</span> <span class="variable">$u</span></span></span><br><span class="line"><span class="meta prompt_">	# </span><span class="language-bash">添加用户</span></span><br><span class="line">	useradd $u</span><br><span class="line"><span class="meta prompt_">	#</span><span class="language-bash">初始化密码</span></span><br><span class="line">	echo &quot;123456&quot; | passwd --stdin $u &amp;&gt;/dev/null</span><br><span class="line">	[ $? -eq 0 ] &amp;&amp; echo &quot;添加用户&quot;$u&quot;初始化密吗成功”</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031806644.png" alt="image-20240203172705194"></p>
<h5 id="计算linux系统所有进程占用内存大小的和"><a href="#计算linux系统所有进程占用内存大小的和" class="headerlink" title="计算linux系统所有进程占用内存大小的和"></a>计算linux系统所有进程占用内存大小的和</h5><p>1.查看进程内存大小</p>
<p><code>ps-aux</code></p>
<p>2.可以看到有多列，RSS这列表示所占内存大小。提取RSS这列并去掉RSS这行</p>
<p><code>ps -aux | awk &#39;&#123;print $6&#125;&#39; | grep -v &#39;RSS&#39;</code></p>
<p>3.统计进程大小之和</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">统计linux系统中所有进程所占内存大小之和</span></span><br><span class="line">ps_aux=$(ps -aux | awk &#x27;&#123;print $6&#125;&#x27; | grep -v &#x27;RSS&#x27;)</span><br><span class="line">sum=0</span><br><span class="line">for n in $ps_aux</span><br><span class="line">do</span><br><span class="line">	sum=$[ $sum + $n ]</span><br><span class="line">done</span><br><span class="line">sum=$[ $sum / 1024 ]</span><br><span class="line">echo &quot;所占内存：$sum&quot;&quot;M&quot;</span><br></pre></td></tr></table></figure>
<h4 id="【示例】统计系统中各种类型的shell并按降序排序显示"><a href="#【示例】统计系统中各种类型的shell并按降序排序显示" class="headerlink" title="【示例】统计系统中各种类型的shell并按降序排序显示"></a>【示例】统计系统中各种类型的shell并按降序排序显示</h4><p>在awk中数组叫做关联数组(associative arrays)。awk中的<strong>数组不必提前声明，也不必声明大小</strong>。数组元素用0或空字符串来初始化，这根据上下文而定。</p>
<p>1.awk中的数组赋值并获取</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031806645.png" alt="image-20240203174731249"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031806646.png" alt="image-20240203175457931"></p>
<p>2.统计系统中各种类型的shell并按降序排序显示</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402031806647.png" alt="image-20240203180533631"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://huaiyuechusan.github.io">SanShui</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://huaiyuechusan.github.io/archives/d8093044.html">https://huaiyuechusan.github.io/archives/d8093044.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://huaiyuechusan.github.io" target="_blank">SanShui的个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Liunx/">Liunx</a><a class="post-meta__tags" href="/tags/Shell%E8%84%9A%E6%9C%AC/">Shell脚本</a></div><div class="post_share"><div class="social-share" data-image="http://wallpaper.csun.site/?19" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/img/wechat.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/img/alipay.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/archives/3cc384d0.html"><img class="prev-cover" src="http://wallpaper.csun.site/?8" onerror="onerror=null;src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Linux环境编程基础</div></div></a></div><div class="next-post pull-right"><a href="/archives/9ac21f23.html"><img class="next-cover" src="http://wallpaper.csun.site/?9" onerror="onerror=null;src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">本地基于知识库的大模型的使用教程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/archives/3cc384d0.html" title="Linux环境编程基础"><img class="cover" src="http://wallpaper.csun.site/?8" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">Linux环境编程基础</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81OTEzMS8zNTU5Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg" onerror="this.onerror=null;this.src='/./img/config_img/%E8%93%9D%E5%A4%A9.jpg'" alt="avatar"/></div><div class="author-info__name">SanShui</div><div class="author-info__description">今天不学习，明天变垃圾</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><a id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/huaiyuechusan"><i class="fa-sharp fa-solid fa-plane"></i><span>欢迎关注我的Github</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/huaiyuechusan" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://huaiyuechusan.github.io/atom.xml" target="_blank" title=""><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到SanShui的博客</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#ShellScript%E8%84%9A%E6%9C%AC%E7%BC%96%E7%A8%8B"><span class="toc-text">ShellScript脚本编程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Shell%E8%84%9A%E6%9C%AC%E5%85%A5%E9%97%A8"><span class="toc-text">Shell脚本入门</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Shell%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-text">Shell是什么</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Shell%E7%9A%84%E8%BF%90%E8%A1%8C%E8%BF%87%E7%A8%8B"><span class="toc-text">Shell的运行过程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Shell%E8%A7%A3%E6%9E%90%E5%99%A8"><span class="toc-text">Shell解析器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Shell%E7%BC%96%E5%86%99%E6%A0%BC%E5%BC%8F%E4%B8%8E%E6%89%A7%E8%A1%8C%E6%96%B9%E5%BC%8F"><span class="toc-text">Shell编写格式与执行方式</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%84%9A%E6%9C%AC%E6%A0%BC%E5%BC%8F"><span class="toc-text">脚本格式</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%84%9A%E6%9C%AC%E6%96%87%E4%BB%B6%E6%89%A7%E8%A1%8C%E7%9A%84%E4%B8%89%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="toc-text">脚本文件执行的三种方式</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A7%A3%E9%87%8A%E6%89%A7%E8%A1%8C%E5%A4%9A%E4%B8%AA%E5%91%BD%E4%BB%A4"><span class="toc-text">解释执行多个命令</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Shell%E5%8F%98%E9%87%8F"><span class="toc-text">Shell变量</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B3%BB%E7%BB%9F%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F"><span class="toc-text">系统环境变量</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Shell%E7%9A%84%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E5%88%86%E7%B1%BB"><span class="toc-text">Shell的配置文件分类</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">环境变量的分类</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E7%9C%8B%E5%BD%93%E5%89%8DShell%E7%B3%BB%E7%BB%9F%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F"><span class="toc-text">查看当前Shell系统环境变量</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E7%9C%8B%E6%89%80%E6%9C%89%E5%8F%98%E9%87%8F"><span class="toc-text">查看所有变量</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E7%B3%BB%E7%BB%9F%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F"><span class="toc-text">常用系统环境变量</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F"><span class="toc-text">自定义变量</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F%E5%88%86%E7%B1%BB"><span class="toc-text">自定义变量分类</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="toc-text">自定义局部变量</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E5%AE%9A%E4%B9%89%E8%A7%84%E5%88%99"><span class="toc-text">变量定义规则</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F%E8%AF%AD%E6%B3%95"><span class="toc-text">定义变量语法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E7%9C%8B%E5%8F%98%E9%87%8F"><span class="toc-text">查看变量</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E5%8F%98%E9%87%8F"><span class="toc-text">删除变量</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="toc-text">自定义全局变量</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%88%B6%E5%AD%90Shell%E7%8E%AF%E5%A2%83%E4%BB%8B%E7%BB%8D"><span class="toc-text">父子Shell环境介绍</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F-1"><span class="toc-text">自定义全局变量</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%B3%BB%E7%BB%9F%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F"><span class="toc-text">自定义系统环境变量</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E7%AC%A6%E5%8F%B7%E5%8F%98%E9%87%8F"><span class="toc-text">特殊符号变量</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E7%AC%A6%E5%8F%B7%E5%8F%98%E9%87%8F%EF%BC%9A-n"><span class="toc-text">特殊符号变量：$n</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E7%AC%A6%E5%8F%B7%E5%8F%98%E9%87%8F%EF%BC%9A-%E5%92%8C"><span class="toc-text">特殊符号变量：$#和$*</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E7%AC%A6%E5%8F%B7%E5%8F%98%E9%87%8F-1"><span class="toc-text">特殊符号变量$?</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E7%AC%A6%E5%8F%B7"><span class="toc-text">特殊符号$$$$</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%8F%98%E9%87%8F"><span class="toc-text">字符串变量</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%88%9B%E5%BB%BA"><span class="toc-text">字符串创建</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E9%95%BF%E5%BA%A6"><span class="toc-text">获取字符串的长度</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#awk%E4%B8%AD%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">awk中循环语句的使用</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#sort"><span class="toc-text">sort</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E3%80%90%E7%A4%BA%E4%BE%8B%E3%80%91sort%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">【示例】sort的使用</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E3%80%90%E7%A4%BA%E4%BE%8B%E3%80%91sort%E7%9A%84-u%E9%80%89%E9%A1%B9"><span class="toc-text">【示例】sort的-u选项</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E3%80%90%E7%A4%BA%E4%BE%8B%E3%80%91sort%E7%9A%84-r%E9%80%89%E9%A1%B9"><span class="toc-text">【示例】sort的-r选项</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E3%80%90%E7%A4%BA%E4%BE%8B%E3%80%91sort%E7%9A%84-o%E9%80%89%E9%A1%B9"><span class="toc-text">【示例】sort的-o选项</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E3%80%90%E7%A4%BA%E4%BE%8B%E3%80%91sort%E7%9A%84-n%E9%80%89%E9%A1%B9"><span class="toc-text">【示例】sort的-n选项</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E3%80%90%E7%A4%BA%E4%BE%8B%E3%80%91sort%E7%9A%84-t%E9%80%89%E9%A1%B9%E5%92%8C-k%E9%80%89%E9%A1%B9"><span class="toc-text">【示例】sort的-t选项和-k选项</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#tee"><span class="toc-text">tee</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A1%88%E4%BE%8B"><span class="toc-text">案例</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%89%B9%E9%87%8F%E4%BF%AE%E6%94%B9%E6%96%87%E4%BB%B6"><span class="toc-text">批量修改文件</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%89%B9%E9%87%8F%E5%88%9B%E5%BB%BA%E7%94%A8%E6%88%B7"><span class="toc-text">批量创建用户</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%AE%A1%E7%AE%97linux%E7%B3%BB%E7%BB%9F%E6%89%80%E6%9C%89%E8%BF%9B%E7%A8%8B%E5%8D%A0%E7%94%A8%E5%86%85%E5%AD%98%E5%A4%A7%E5%B0%8F%E7%9A%84%E5%92%8C"><span class="toc-text">计算linux系统所有进程占用内存大小的和</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E3%80%90%E7%A4%BA%E4%BE%8B%E3%80%91%E7%BB%9F%E8%AE%A1%E7%B3%BB%E7%BB%9F%E4%B8%AD%E5%90%84%E7%A7%8D%E7%B1%BB%E5%9E%8B%E7%9A%84shell%E5%B9%B6%E6%8C%89%E9%99%8D%E5%BA%8F%E6%8E%92%E5%BA%8F%E6%98%BE%E7%A4%BA"><span class="toc-text">【示例】统计系统中各种类型的shell并按降序排序显示</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/archives/6ca065c5.html" title="SanShui API 使用教程"><img src="http://wallpaper.csun.site/?abc" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="SanShui API 使用教程"/></a><div class="content"><a class="title" href="/archives/6ca065c5.html" title="SanShui API 使用教程">SanShui API 使用教程</a><time datetime="2025-03-13T13:21:12.311Z" title="更新于 2025-03-13 21:21:12">2025-03-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/b5700173.html" title="微信小程序定时订阅消息问题"><img src="http://wallpaper.csun.site/?25" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="微信小程序定时订阅消息问题"/></a><div class="content"><a class="title" href="/archives/b5700173.html" title="微信小程序定时订阅消息问题">微信小程序定时订阅消息问题</a><time datetime="2024-10-17T12:04:53.379Z" title="更新于 2024-10-17 20:04:53">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/638889b7.html" title="深度学习回归任务训练代码模版"><img src="http://wallpaper.csun.site/?24" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="深度学习回归任务训练代码模版"/></a><div class="content"><a class="title" href="/archives/638889b7.html" title="深度学习回归任务训练代码模版">深度学习回归任务训练代码模版</a><time datetime="2024-10-17T12:04:09.066Z" title="更新于 2024-10-17 20:04:09">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/7cb9f0a8.html" title="通过nginx访问tomcat中SpringMVC应用"><img src="http://wallpaper.csun.site/?23" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="通过nginx访问tomcat中SpringMVC应用"/></a><div class="content"><a class="title" href="/archives/7cb9f0a8.html" title="通过nginx访问tomcat中SpringMVC应用">通过nginx访问tomcat中SpringMVC应用</a><time datetime="2024-10-17T12:02:23.321Z" title="更新于 2024-10-17 20:02:23">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/d4b1abad.html" title="下载M3U8格式加密视频"><img src="http://wallpaper.csun.site/?22" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="下载M3U8格式加密视频"/></a><div class="content"><a class="title" href="/archives/d4b1abad.html" title="下载M3U8格式加密视频">下载M3U8格式加密视频</a><time datetime="2024-10-17T12:02:02.720Z" title="更新于 2024-10-17 20:02:02">2024-10-17</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('http://wallpaper.csun.site/?19')"><div id="footer-wrap"><div class="footer_custom_text">更多内容查看<a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/huaiyuechusan/">我的GitHub</a> ！</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.1
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container').forEach(node => {
            if (node.hasAttribute('display')) {
              btf.wrap(node, 'div', { class: 'mathjax-overflow' })
            } else {
              btf.wrap(node, 'span', { class: 'mathjax-overflow' })
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !true) {
  if (true) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><div class="aplayer no-destroy" data-id="875151895" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-volume="0.5"> </div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="Nice,To,Meet,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:32.3%;}.categoryBar-list{max-height: 380px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 320px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(./img/config_img/image-20231112202739060-2023-11-1220-27-56.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/AI大模型/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">AI大模型</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/202310300007012-2023-11-1123-30-55.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/微信小程序/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">微信小程序</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Girl-2023-11-2221_46_26.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/爬虫/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">爬虫</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/202310300007316-2023-11-1123-30-57.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/深度学习/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">深度学习</a><span class="categoryBar-list-count">4</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Cat-2023-11-2221-47-16.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/大数据/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">大数据</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-36-46.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/PyTorch/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">PyTorch</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-36-11.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/多模态推荐系统/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">多模态推荐系统</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Starry-Night-in-Anime-Wallpaper-2023-11-2221-46-39.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/学习总结/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">学习总结</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/page_img/wallhaven-y8lqo7.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/竞赛/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">竞赛</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-34-25.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Python/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">Python</a><span class="categoryBar-list-count">4</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-37-57.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Liunx/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">Liunx</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="博客框架为Hexo_v6.2.0" title=""><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="主题版本Butterfly_v4.3.1" title=""><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用多线部署，主线路托管于Github Pages" title=""><img src="https://img.shields.io/badge/Hosted-Github Pages-brightgreen?style=flat&amp;logo=Github" alt=""/></a><a class="github-badge" target="_blank" href="https://gitee.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用多线部署，备用线路托管于Gitee Pages" title=""><img src="https://img.shields.io/badge/Hosted-Gitee Pages-22DDDD?style=flat&amp;logo=Gitee" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站项目由Github托管" title=""><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&amp;logo=GitHub" alt=""/></a><a class="github-badge" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可" title=""><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&amp;logo=Claris" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="/./js/runtime.js"></script><!-- hexo injector body_end end --></body></html>